package org.jeecgframework.web.service.impl;

import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.service.ZyInspectionPlanServiceI;
import org.jeecgframework.web.service.ZyWorkFlowService;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.SendMailUtil;
import org.jeecgframework.web.util.SendMessage;
import org.jeecgframework.web.util.StaticValue;
import org.jeecgframework.workflow.service.ActivitiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.*;

@Service("zyInspectionPlanService")
@Transactional
public class ZyInspectionPlanServiceImpl extends CommonServiceImpl implements ZyInspectionPlanServiceI {

    private static final Logger logger = Logger.getLogger ( ZyInspectionPlanServiceImpl.class );

    @Autowired
    private SystemService systemService;
    @Autowired
    private ZyWorkFlowService zyWorkFlowService;
    @Autowired
    private ZyCommonService zyCommonService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private ActivitiService activitiService;
    @Autowired
    private TaskService taskService;


    public <T> void delete(T entity) {
        super.delete ( entity );
        //执行删除操作配置的sql增强
        this.doDelSql ( (ZyInspectionPlanEntity) entity );
    }

    public <T> Serializable save(T entity) {
        Serializable t = super.save ( entity );
        //执行新增操作配置的sql增强
        this.doAddSql ( (ZyInspectionPlanEntity) entity );
        return t;
    }

    public <T> void saveOrUpdate(T entity) {
        super.saveOrUpdate ( entity );
        //执行更新操作配置的sql增强
        this.doUpdateSql ( (ZyInspectionPlanEntity) entity );
    }

    /**
     * 默认按钮-sql增强-新增操作
     *
     * @return
     */
    public boolean doAddSql(ZyInspectionPlanEntity t) {
        return true;
    }

    /**
     * 默认按钮-sql增强-更新操作
     *
     * @return
     */
    public boolean doUpdateSql(ZyInspectionPlanEntity t) {
        return true;
    }

    /**
     * 默认按钮-sql增强-删除操作
     *
     * @return
     */
    public boolean doDelSql(ZyInspectionPlanEntity t) {
        return true;
    }

    /**
     * 替换sql中的变量
     *
     * @param sql
     * @return
     */
    public String replaceVal(String sql, ZyInspectionPlanEntity t) {
        sql = sql.replace ( "#{id}", String.valueOf ( t.getId () ) );
        sql = sql.replace ( "#{plan_id}", String.valueOf ( t.getPlanId () ) );
        sql = sql.replace ( "#{equipment_spare_id}", String.valueOf ( t.getEquipmentSpare ().getId () ) );
        sql = sql.replace ( "#{order_begin_time}", String.valueOf ( t.getOrderBeginTime () ) );
        sql = sql.replace ( "#{order_end_time}", String.valueOf ( t.getOrderEndTime () ) );
        sql = sql.replace ( "#{actual_date}", String.valueOf ( t.getActualDate () ) );
        sql = sql.replace ( "#{company}", String.valueOf ( t.getCompany () ) );
        sql = sql.replace ( "#{engineer}", String.valueOf ( t.getEngineer () ) );
        sql = sql.replace ( "#{engineer_order_time}", String.valueOf ( t.getEngineerOrderTime () ) );
        sql = sql.replace ( "#{light_path}", String.valueOf ( t.getLightPath () ) );
        sql = sql.replace ( "#{plan_quarter}", String.valueOf ( t.getPlanQuarter () ) );
        sql = sql.replace ( "#{state}", String.valueOf ( t.getState () ) );
        sql = sql.replace ( "#{remarks}", String.valueOf ( t.getRemarks () ) );
        sql = sql.replace ( "#{create_name}", String.valueOf ( t.getCreateName () ) );
        sql = sql.replace ( "#{create_by}", String.valueOf ( t.getCreateBy () ) );
        sql = sql.replace ( "#{create_date}", String.valueOf ( t.getCreateDate () ) );
        sql = sql.replace ( "#{update_name}", String.valueOf ( t.getUpdateName () ) );
        sql = sql.replace ( "#{update_by}", String.valueOf ( t.getUpdateBy () ) );
        sql = sql.replace ( "#{update_date}", String.valueOf ( t.getUpdateDate () ) );
        sql = sql.replace ( "#{UUID}", UUID.randomUUID ().toString () );
        return sql;
    }

    public void generatePlanId(ZyInspectionPlanEntity zyInspectionPlanEntity, String parentId) {
        Calendar calendar = Calendar.getInstance ();
        StringBuffer sb = new StringBuffer ();
        char maxSign = 0;
        //生成子单巡检计划PLANID
        if (StringUtil.isNotEmpty ( parentId )) {
            Map<String, Object> currZyIp = findOneForJdbc ( "SELECT plan_id FROM zy_inspection_plan WHERE id = ?", parentId );
            List<ZyInspectionPlanEntity> zyInspectionPlans = systemService.findHql ( "FROM ZyInspectionPlanEntity WHERE zyIp.id =? ORDER BY planId DESC ", parentId );
            String currPlanId = "";
            if (zyInspectionPlans != null && zyInspectionPlans.size () > 0) {
                ZyInspectionPlanEntity zyIp = zyInspectionPlans.get ( 0 );
                currPlanId = zyIp.getPlanId ();
                maxSign = currPlanId.charAt ( currPlanId.length () - 1 );
                ++maxSign;
            } else {
                maxSign = 'A';
            }
            sb.append ( currZyIp.get ( "plan_id" ).toString () ).append ( maxSign );
        } else {
            //普通巡检计划PLANID
            //PM + 年份 + 五位数字（默认从1增长）
            String sign = "PM";
            Integer currYear = Integer.valueOf ( String.valueOf ( calendar.get ( Calendar.YEAR ) ).substring ( 2 ) );//当前年份后两位
            sb.append ( sign );
            Map<String, Object> rsMap = super.findOneForJdbc ( "SELECT PLAN_ID FROM zy_inspection_plan WHERE ISNULL(parent_ip_id) AND plan_id LIKE '" + sign + currYear + "%' ORDER BY plan_id DESC LIMIT 0,1" );
            String partThree;
            if (null != rsMap && StringUtil.isNotEmpty ( rsMap.get ( "PLAN_ID" ) )) {
                String currPlanId = rsMap.get ( "PLAN_ID" ).toString ();
                Integer existMaxYear = Integer.valueOf ( currPlanId.substring ( 2, 4 ) );
                sb.append ( existMaxYear );
                Long maxIdLong = Long.valueOf ( currPlanId.substring ( 4 ) );
                Long currMaxIdLong = maxIdLong + 1;
                if (currMaxIdLong >= 1 && currMaxIdLong <= 9) {
                    sb.append ( "00000" ).append ( currMaxIdLong );
                } else if (currMaxIdLong >= 10 && currMaxIdLong <= 99) {
                    sb.append ( "0000" ).append ( currMaxIdLong );
                } else if (currMaxIdLong >= 100 && currMaxIdLong <= 999) {
                    sb.append ( "000" ).append ( currMaxIdLong );
                } else if (currMaxIdLong >= 1000 && currMaxIdLong <= 9999) {
                    sb.append ( "00" ).append ( currMaxIdLong );
                } else if (currMaxIdLong >= 10000 && currMaxIdLong <= 99999) {
                    sb.append ( "0" ).append ( currMaxIdLong );
                } else if (currMaxIdLong >= 10000 && currMaxIdLong <= 999999) {
                    sb.append ( currMaxIdLong );
                }
            } else {
                //初始化
                partThree = "000001";
                sb.append ( currYear ).append ( partThree );
            }
        }
        zyInspectionPlanEntity.setPlanId ( sb.toString () );
    }

    @Override
    public String getIpQuarterByMonth(String ipMonth) {
        String planQuarter = StaticValue.DIC_PLAN_INSPECTION_QUARTER_ONE;
        if (StringUtil.isNotEmpty ( ipMonth )) {
            switch (ipMonth) {
                case "1":
                case "2":
                case "3":
                    planQuarter = StaticValue.DIC_PLAN_INSPECTION_QUARTER_ONE;
                    break;
                case "4":
                case "5":
                case "6":
                    planQuarter = StaticValue.DIC_PLAN_INSPECTION_QUARTER_TWO;
                    break;
                case "7":
                case "8":
                case "9":
                    planQuarter = StaticValue.DIC_PLAN_INSPECTION_QUARTER_THREE;
                    break;
                case "10":
                case "11":
                case "12":
                    planQuarter = StaticValue.DIC_PLAN_INSPECTION_QUARTER_FOUR;
                    break;
            }
        }
        return planQuarter;
    }

    @Override
    public void batchGeneratePlan(ZyInspectionPlanEntity zyInspectionPlan, String equipmentIds, String parentId, String zyIpId) {
        try {
            if (StringUtil.isNotEmpty ( equipmentIds )) {
                String[] equipmentIdsArr = equipmentIds.split ( "," );
                if (equipmentIdsArr.length > 0) {
                    String ipMonth = zyInspectionPlan.getIpMonth ();
                    zyInspectionPlan.setPlanQuarter ( this.getIpQuarterByMonth ( ipMonth ) );//保留巡检季度，根据巡检月份计算
                    Calendar cal = Calendar.getInstance ();
                    int currYear = cal.get ( Calendar.YEAR );
                    zyInspectionPlan.setIpPlanDate ( DateUtils.str2Date ( currYear + "-" + ipMonth + "-01", DateUtils.date_sdf ) );//设置巡检日期，默认给每个月的 1号为巡检日期
                    for (String eqId : equipmentIdsArr) {
                        String prRemark = "";
                        ZyInspectionPlanEntity zyIP = null;
                        if (StringUtil.isNotEmpty ( zyIpId )) {//如果有值 则为 第三方巡检单位拒绝后重新指派巡检单位
                            zyIP = systemService.getEntity ( ZyInspectionPlanEntity.class, zyIpId );
                            MyBeanUtils.copyBeanNotNull2Bean ( zyInspectionPlan, zyIP );
                            zyIP.setId ( zyIpId );
                            ZyContactsEntity zyContacter = systemService.getEntity ( ZyContactsEntity.class, zyIP.getContacter ().getId () );
                            zyIP.setCompanyHadAreaEg ( zyCommonService.judgeCompanyHadAreaEnginee ( zyIP.getCompany (), zyIP.getLightPath () ) ? "1" : "0" );
//                            zyWorkFlowService.processComplete ( "1", zyIP.getProcesssId (), zyContacter.getTsBaseUser ().getUserName (), "1", "userId" );
                            prRemark = "巴可主管重新指派第三方巡检单位，备注：" + zyIP.getRemarks ();
                            zyIP.setState ( StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY );
                            super.saveOrUpdate ( zyIP );
                            try {
                                //发送邮件
                                ZyEmailEntity eMail = new ZyEmailEntity ();
                                eMail.setEmailSubject ( "巴可巡检任务分派通知" );
                                eMail.setEmailReceiver ( zyContacter.getEmail () );
                                Map<String, Object> paraMap = new HashMap<String, Object> ();
                                paraMap.put ( "tpHeaderName", zyContacter.getName () );
                                paraMap.put ( "url", StaticValue.HTTP_HEADER );
                                paraMap.put ( "planTaskCount", 1 );
                                SendMailUtil.sendFtlMail ( eMail, "mail_barcoSendToTp.ftl", paraMap, systemService );
                            } catch (Exception e) {
                            }
                        } else {
                            zyIP = new ZyInspectionPlanEntity ();
                            MyBeanUtils.copyBeanNotNull2Bean ( zyInspectionPlan, zyIP );
                            prRemark = "巴可主管生成巡检计划，备注：" + zyIP.getRemarks ();
                            ZyEquipmentSpareEntity t = this.get ( ZyEquipmentSpareEntity.class, eqId );
                            ZyEquipmentSpareEntity equipmentSpare = new ZyEquipmentSpareEntity ();
                            equipmentSpare.setId ( eqId );
                            //如果巡检计划状态已经为true 不更改
                            if (t.getIsHadInspection () == null ||
                                    t.getIsHadInspection ().equals ( "0" )) {
                                //改变设备 为 有巡检计划
                                equipmentSpare.setIsHadInspection ( "1" );
                                // Modify 无论是否有巡检计划，剩余巡检次数都-1 Amy 2018/2/8 start 
                            }
                                Integer residualIpCount = t.getResidualIpCount () == null ? 0 : t.getResidualIpCount ();
                                residualIpCount = residualIpCount != 0 ? --residualIpCount : 0;
                                equipmentSpare.setResidualIpCount ( residualIpCount );
                                MyBeanUtils.copyBeanNotNull2Bean ( equipmentSpare, t );
                                super.saveOrUpdate ( t );
                             // Modify 无论是否有巡检计划，剩余巡检次数都-1 Amy 2018/2/8 end 
                                
                            //生成巡检计划ID
                            this.generatePlanId ( zyIP, parentId );
                            if (StringUtil.isNotEmpty ( parentId )) {
                                ZyInspectionPlanEntity pIp = this.get ( ZyInspectionPlanEntity.class, parentId );
                                zyIP.setZyIp ( pIp );
                            }
                            //关联设备
                            zyIP.setEquipmentSpare ( t );
                            //设置巡检计划状态
                            zyIP.setState ( StaticValue.DIC_PLAN_STATE_TODO );
                            //初始化 工程师修改预约上门时间次数 0
                            zyIP.setEngineerOrderTimeCount ( 0 );
                            //设置巡检单位是否有区域工程师，为后续首页显示代办以及其他地方方便判断取值
                            zyIP.setCompanyHadAreaEg ( zyCommonService.judgeCompanyHadAreaEnginee ( zyIP.getCompany (), zyIP.getLightPath () ) ? "1" : "0" );
                            zyIP.setGenerateSource ( StaticValue.DIC_GENERATE_SOURCE_MANUAL );//设置生成方式为 手动生成
                            zyIP.setCanUpdateOrdertime ( "1" );//是否可以修改巡检年月默认1（微信用）
                            super.save ( zyIP );
                        }
                        //更新巡检计划 todo
                        //保存巡检计划流程记录
                        ZyPlanRecordEntity zyPlanRecord = new ZyPlanRecordEntity ();
                        zyPlanRecord.setBusId ( zyIP.getId () );
                        zyPlanRecord.setPlanState ( zyIP.getState () );
                        zyPlanRecord.setRemark ( prRemark );
                        systemService.save ( zyPlanRecord );
                    }

                }
            }
            systemService.addLog ( "生成巡检计划成功", Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO );
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }


//	public void doBatchSendPlan(HttpServletRequest request) {
//		String remarks = oConvertUtils.getString(request.getParameter("remarks"));
//		String planIds = oConvertUtils.getString(request.getParameter("planIds"));
//		try {
//			String[] planIdsArr = planIds.split(",");
//			if(planIdsArr != null && planIdsArr.length > 0){
//				ZyContactsEntity zyContacter = null;
//				String barcoServerDirectors = "";
//				for (String planId : planIdsArr) {
//					ZyInspectionPlanEntity zyIP = this.get(ZyInspectionPlanEntity.class, planId);
//					String processInsId = "";
//					if(!zyIP.getState().equals(StaticValue.DIC_PLAN_STATE_THIRDPARTY_REFUSED)){
//						////启动流程
//						Map<String, Object> paramsMap = new HashMap<String, Object>();
//						//设置巴可服务商主管
//						barcoServerDirectors = !barcoServerDirectors.equals("") ?
//								barcoServerDirectors : zyCommonService.queryUserNamesByOrgCodeAndRoleCode(StaticValue.ORG_CODE_BARCO,StaticValue.RULE_CODE_BARCO_SERVER_DIRECTOR);
//						paramsMap.put(StaticValue.P_FORM_ZY_INSPECTION_PLAN_NODE01_USER, barcoServerDirectors);
//						//查询巡检计划第三方负责人
//						zyContacter = zyContacter != null ? zyContacter : super.get(ZyContactsEntity.class, zyIP.getContacter().getId());
//						//设置第三方负责人
//						String thirdPartyHeader = zyContacter.getTsBaseUser().getUserName();
//						paramsMap.put(StaticValue.P_FORM_ZY_INSPECTION_PLAN_NODE02_USER, thirdPartyHeader);
//						///启动流程
//						ProcessInstance processInstance = zyWorkFlowService.startOnlineProcess(StaticValue.P_FORM_ZY_INSPECTION_PLAN, zyIP.getId(),paramsMap);
//						processInsId = processInstance.getId();
//					}else{
//						processInsId = zyIP.getProcesssId();
//					}
//					///并 完成 分配巡检计划 这步
//					Map<String, Object> returnMap = zyWorkFlowService.processComplete(ResourceUtil.getSessionUserName().getUserName(),"1",processInsId,"","","");
//					//保留流程id 到 巡检计划表
//					zyIP.setProcesssId(processInsId);
//					super.saveOrUpdate(zyIP);
//
//					//更新巡检计划状态
//					zyIP.setState(StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY);
//					zyIP.setSendToTpTime(new Date());
//					saveOrUpdate(zyIP);
//					//保存巡检计划流程记录
//					ZyPlanRecordEntity zyPlanRecord = new ZyPlanRecordEntity();
//					zyPlanRecord.setBusId(zyIP.getId());
//					zyPlanRecord.setPlanState(zyIP.getState());
//					zyPlanRecord.setProcInsId(zyIP.getProcesssId());
//					zyPlanRecord.setRemark(remarks);
//					zyPlanRecord.setTsUser(ResourceUtil.getSessionUserName());
//					zyPlanRecord.setTaskId(((Task)returnMap.get("task")).getId());;
//					systemService.save(zyPlanRecord);
//				}
//				try {
//					//发送邮件
//					ZyEmailEntity eMail = new ZyEmailEntity();
//					eMail.setEmailSubject("巴可巡检任务分派通知");
//					eMail.setEmailReceiver(zyContacter.getEmail());
//					Map<String, Object> paraMap = new HashMap<String, Object>();
//					paraMap.put("tpHeaderName", zyContacter.getName());
//					paraMap.put("url", StaticValue.HTTP_HEADER);
//					paraMap.put("planTaskCount", planIdsArr.length);
//					SendMailUtil.sendFtlMail(eMail, "mail_barcoSendToTp.ftl", paraMap);
//	systemService.addLog("发送邮件,接受方:" + eMail.getEmailReceiver() + ",内容:" + eMail, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);
//				} catch (Exception e) {
//				}
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}


//	public AjaxJson doBatchSendPlan(HttpServletRequest request) {
//		AjaxJson j = new AjaxJson();
//		boolean flag = true;
//		String msg = "分配成功";
//		String planIds = oConvertUtils.getString(request.getParameter("planIds"));
//		String remarks = oConvertUtils.getString(request.getParameter("remarks"));
//		try {
//			String[] planIdsArr = planIds.split(",");
//			if(planIdsArr != null && planIdsArr.length > 0){
//				System.out.println("开始更新巡检计划，总计：" + planIdsArr.length + "条");
//				int count = 1;
//				for (String id : planIdsArr) {
//					System.out.print("更新第"+ count +"条...\t");
//					ZyInspectionPlanEntity zyIp = super.getEntity(ZyInspectionPlanEntity.class, id);
//					zyIp.setState(StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY);
//					super.saveOrUpdate(zyIp);
//					System.out.println("第"+ count +"条更新完毕");
//					count ++;
//				}
//				System.out.println("更新完毕，开始启动线程...");
//				TSUser user = ResourceUtil.getSessionUserName();
//				ThreadLocal<HttpServletRequest> req = new ThreadLocal<HttpServletRequest>();
//				req.set(request);
//				ZyProcessMainThread mainThread = new ZyProcessMainThread(planIdsArr, user, remarks);
//				mainThread.start();
//				System.out.println("线程启动完毕，后台运行中");
//			}
//		} catch (Exception e) {
//			msg = "分配异常";
//			flag = false;
//			e.printStackTrace();
//			System.err.println("事务出现异常,回滚事务！");
//			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//此处采用手动回滚
//		}
//		j.setMsg(msg);
//		j.setSuccess(flag);
//		return j;
//	}


    public AjaxJson doBatchSendPlan(HttpServletRequest request) {
        AjaxJson j = new AjaxJson ();
        boolean flag = true;
        String msg = "分配成功";
        String planIds = oConvertUtils.getString ( request.getParameter ( "planIds" ) );
        String remarks = oConvertUtils.getString ( request.getParameter ( "remarks" ) );
        try {
            String[] planIdsArr = planIds.split ( "," );
            if (planIdsArr != null && planIdsArr.length > 0) {
                System.out.println ( "开始更新巡检计划，总计：" + planIdsArr.length + "条" );
                int count = 1;
                for (String id : planIdsArr) {
                    System.out.print ( "更新第" + count + "条...\t" );
                    ZyInspectionPlanEntity zyIp = super.getEntity ( ZyInspectionPlanEntity.class, id );
                    /**
                     * 如果是待处理，那么 先更新为分派到第三方；如果是第三方拒绝的 这里不需要设置状态。会在ZyProcessThread 中设置，因为在ZyProcessThread中需要根据状态判断是否需要启动流程
                     */
                    if (zyIp.getState ().equals ( StaticValue.DIC_PLAN_STATE_TODO )) {
                        zyIp.setState ( StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY );
                    }
                    super.saveOrUpdate ( zyIp );
                    System.out.println ( "第" + count + "条更新完毕" );
                    count++;
                }
                System.out.println ( "更新完毕，开始启动线程..." );
                TSUser user = ResourceUtil.getSessionUserName ();
                ThreadLocal<HttpServletRequest> req = new ThreadLocal<HttpServletRequest> ();
                req.set ( request );
                ZyProcessMainThread mainThread = new ZyProcessMainThread ( planIdsArr, user, remarks );
                mainThread.start ();
                System.out.println ( "线程启动完毕，后台运行中" );
            }
        } catch (Exception e) {
            msg = "分配异常";
            flag = false;
            e.printStackTrace ();
            System.err.println ( "事务出现异常,回滚事务！" );
            TransactionAspectSupport.currentTransactionStatus ().setRollbackOnly ();//此处采用手动回滚
        }
        j.setMsg ( msg );
        j.setSuccess ( flag );
        return j;
    }

    private List<Map<String, Object>> queryForAreaEngineers(String orgCode, String roleCode, List<String> authentications, String state) {
        StringBuffer sql = new StringBuffer ();
        sql.append ( " SELECT " );
        sql.append ( " eg.id, eg.`name`, eg.cellphone, eg.email, eg.state, eg.authentication" );
        sql.append ( " FROM  " );
        sql.append ( " t_s_base_user bu  " );
        sql.append ( " LEFT JOIN zy_engineer eg on eg.ts_base_user_id = bu.ID  " );
        sql.append ( " LEFT JOIN t_s_user_org uo on uo.user_id = bu.ID  " );
        sql.append ( " LEFT JOIN t_s_depart dp on dp.ID = uo.org_id  " );
        sql.append ( " LEFT JOIN t_s_role_user ru on ru.userid = bu.ID  " );
        sql.append ( " LEFT JOIN t_s_role ro on ro.ID = ru.roleid  " );
        sql.append ( " WHERE  " );
        sql.append ( " dp.org_code LIKE '" ).append ( orgCode ).append ( "%'  " );
        sql.append ( " AND dp.logic_delete = 0 " );
        sql.append ( " AND ro.rolecode = '" ).append ( roleCode ).append ( "' " );
        sql.append ( " AND eg.state = '" ).append ( state ).append ( "' " );
        sql.append ( " AND eg.is_delete = 0 " );
        sql.append ( "AND (" );
        for (int i = 0; i < authentications.size (); i++) {
            if (i == authentications.size () - 1) {
                sql.append ( " eg.authentication = '" ).append ( authentications.get ( i ) ).append ( "')" );
            } else {
                sql.append ( " eg.authentication = '" ).append ( authentications.get ( i ) ).append ( "' OR" );
            }
        }
        return super.findForJdbc ( sql.toString () );
    }

    /**
     * @param request
     * @param dataGrid
     * @param orgCode  组织权限code
     * @param roleCode 角色code
     * @param state    工程师状态
     * @return
     * @author xiul
     * 2016-4-18 下午8:27:18
     * Description 第三方负责人分配工程师 dataGrid列表查询
     */
    private void queryForAreaEngineerByOrgCodeAndRoleCode(HttpServletRequest request, DataGrid dataGrid, String orgCode, String roleCode, List<String> authentications, String state) {
        StringBuffer sql = new StringBuffer ();
        sql.append ( " SELECT " );
        sql.append ( " eg.id, eg.`name`, eg.cellphone, eg.email, eg.state, eg.authentication" );
        sql.append ( " FROM  " );
        sql.append ( " t_s_base_user bu  " );
        sql.append ( " LEFT JOIN zy_engineer eg ON eg.ts_base_user_id = bu.ID  " );
        sql.append ( " LEFT JOIN t_s_user_org uo ON uo.user_id = bu.ID  " );
        sql.append ( " LEFT JOIN t_s_depart dp ON dp.ID = uo.org_id  " );
        sql.append ( " LEFT JOIN t_s_role_user ru ON ru.userid = bu.ID  " );
        sql.append ( " LEFT JOIN t_s_role ro ON ro.ID = ru.roleid  " );
        sql.append ( " WHERE  " );
        sql.append ( " dp.org_code LIKE '" ).append ( orgCode ).append ( "%' " );
        sql.append ( " AND dp.logic_delete = 0 " );
        sql.append ( " AND ro.rolecode = '" ).append ( roleCode ).append ( "' " );
        sql.append ( " AND eg.state = '" ).append ( state ).append ( "' " );
        sql.append ( " AND eg.is_delete = 0 " );
        sql.append ( "AND (" );
        for (int i = 0; i < authentications.size (); i++) {
            if (i == authentications.size () - 1) {
                sql.append ( " eg.authentication = '" ).append ( authentications.get ( i ) ).append ( "')" );
            } else {
                sql.append ( " eg.authentication = '" ).append ( authentications.get ( i ) ).append ( "' OR" );
            }
        }
        Map<String, String[]> paramsMap = request.getParameterMap ();
        if (StringUtil.isNotEmpty ( paramsMap.get ( "name" ) ) && StringUtil.isNotEmpty ( paramsMap.get ( "name" )[0] )) {
            sql.append ( " AND eg.name LIKE '%" ).append ( paramsMap.get ( "name" )[0].toString () ).append ( "%' " );
        }
        if (StringUtil.isNotEmpty ( paramsMap.get ( "cellphone" ) ) && StringUtil.isNotEmpty ( paramsMap.get ( "cellphone" )[0] )) {
            sql.append ( " AND eg.cellphone LIKE '%" ).append ( paramsMap.get ( "cellphone" )[0].toString () ).append ( "%' " );
        }
        if (StringUtil.isNotEmpty ( paramsMap.get ( "email" ) ) && StringUtil.isNotEmpty ( paramsMap.get ( "email" )[0] )) {
            sql.append ( " AND eg.email LIKE '%" ).append ( paramsMap.get ( "email" )[0].toString () ).append ( "%' " );
        }

        int totalCount = 0;
        Integer page = 1, rows = 10;
        rows = Integer.valueOf ( null != paramsMap.get ( "rows" ) ? paramsMap.get ( "rows" )[0] : "0" );
        page = Integer.valueOf ( null != paramsMap.get ( "page" ) ? paramsMap.get ( "page" )[0] : "0" );
        List<Map<String, Object>> rsMapList = new ArrayList<Map<String, Object>> ();
        if (rows == 0 && page == 0) {
            rsMapList = findForJdbc ( sql.toString () );
        } else {
            dataGrid.setPage ( page );
            dataGrid.setRows ( rows );
            rsMapList = findForJdbc ( sql.toString (), page, rows );
        }
        List<Map<String, Object>> countMapList = super.findForJdbc ( sql.toString () );
        if (null != countMapList && countMapList.size () > 0) {
            totalCount = countMapList.size ();
        }
        dataGrid.setTotal ( totalCount );
        dataGrid.setResults ( rsMapList );
    }

    public void queryDatagridResultForChooseEngineers(HttpServletRequest request, DataGrid dataGrid, String orgCode, String planIds) {
        Criteria c = getSession ().createCriteria ( ZyInspectionPlanEntity.class );
        c.add ( Restrictions.in ( "id", planIds.split ( "," ) ) );
        c.add ( Restrictions.eq ( "lightPath", StaticValue.DIC_LIGHT_PATH_02 ) );
        Integer size = c.list ().size ();
        List<String> authentication = new ArrayList<String> ();
        if (size > 0) {
            authentication = zyCommonService.getEngineerAuthenticationsByLigthPath ( StaticValue.DIC_LIGHT_PATH_02 );
        } else {
            authentication = zyCommonService.getEngineerAuthenticationsByLigthPath ( StaticValue.DIC_LIGHT_PATH_01 );
        }
        queryForAreaEngineerByOrgCodeAndRoleCode ( request, dataGrid, orgCode, StaticValue.RULE_CODE_AREA_ENGINEER, authentication, StaticValue.DIC_ENGINEER_STATE_ONJOB );
        List<Map<String, Object>> results = dataGrid.getResults ();
        if (results == null || results.size () == 0) {
            //没有区域工程师 roleCode 为 RULE_CODE_THIRDPARTY_ENGINEER
            queryForAreaEngineerByOrgCodeAndRoleCode ( request, dataGrid, orgCode, StaticValue.RULE_CODE_THIRDPARTY_ENGINEER, authentication, StaticValue.DIC_ENGINEER_STATE_ONJOB );
        }
    }

    public void queryDatagridResultForChooseContacters(HttpServletRequest request,DataGrid dataGrid, String roleCode) {
        StringBuffer sql = new StringBuffer ();
        sql.append ( " SELECT " );
        sql.append ( " bu.id, " );
        sql.append ( " bu.realname AS name,IFNULL(ct.cellphone1,'') AS cellphone1, IFNULL(ct.cellphone2,'') AS cellphone2, IFNULL(ct.email,'') AS email" );
        sql.append ( " FROM " );
        sql.append ( " t_s_base_user bu " );
        sql.append ( " LEFT JOIN zy_contacts ct on ct.base_id = bu.ID " );
        sql.append ( " LEFT JOIN t_s_user_org uo on uo.user_id = bu.ID " );
        sql.append ( " LEFT JOIN t_s_depart dp on dp.ID = uo.org_id " );
        sql.append ( " LEFT JOIN t_s_role_user ru on ru.userid = bu.ID " );
        sql.append ( " LEFT JOIN t_s_role ro on ro.ID = ru.roleid " );
        sql.append ( " WHERE " );
        sql.append ( " dp.org_code = '" ).append ( roleCode == null ? "" : roleCode ).append ( "' " );
        sql.append ( " AND dp.logic_delete = 0 " );
        sql.append ( " AND ro.rolecode = '" ).append ( StaticValue.RULE_CODE_THIRDPARTY_HEADER ).append ( "'" );
        Map<String, String[]> paramsMap = request.getParameterMap ();
        Integer page = 1, rows = 10;
        rows = Integer.valueOf ( paramsMap.get ( "rows" )[0] );
        page = Integer.valueOf ( paramsMap.get ( "page" )[0] );
        if (StringUtil.isNotEmpty ( paramsMap.get ( "name" ) ) && StringUtil.isNotEmpty ( paramsMap.get ( "name" )[0] )) {
            sql.append ( " AND bu.name LIKE '%" ).append ( paramsMap.get ( "name" )[0].toString () ).append ( "%' " );
        }
        if (StringUtil.isNotEmpty ( paramsMap.get ( "cellphone1" ) ) && StringUtil.isNotEmpty ( paramsMap.get ( "cellphone1" )[0] )) {
            sql.append ( " AND ct.cellphone1 LIKE '%" ).append ( paramsMap.get ( "cellphone1" )[0].toString () ).append ( "%' " );
        }
        if (StringUtil.isNotEmpty ( paramsMap.get ( "cellphone2" ) ) && StringUtil.isNotEmpty ( paramsMap.get ( "cellphone2" )[0] )) {
            sql.append ( " AND ct.cellphone2 LIKE '%" ).append ( paramsMap.get ( "cellphone2" )[0].toString () ).append ( "%' " );
        }
        if (StringUtil.isNotEmpty ( paramsMap.get ( "email" ) ) && StringUtil.isNotEmpty ( paramsMap.get ( "email" )[0] )) {
            sql.append ( " AND ct.email LIKE '%" ).append ( paramsMap.get ( "email" )[0].toString () ).append ( "%' " );
        }
        int totalCount = 0;
        List<Map<String, Object>> rsMapList = new ArrayList<Map<String, Object>> ();
        if (rows == 0 && page == 0) {
            rsMapList = findForJdbc ( sql.toString () );
        } else {
            dataGrid.setPage ( page );
            dataGrid.setRows ( rows );
            rsMapList = findForJdbc ( sql.toString (), page, rows );
        }
        List<Map<String, Object>> countMapList = super.findForJdbc ( sql.toString () );
        if (null != countMapList && countMapList.size () > 0) {
            totalCount = countMapList.size ();
        }
        dataGrid.setTotal ( totalCount );
        dataGrid.setResults ( rsMapList );

    }


    /**
     * @param orgCode  组织权限code
     * @param roleCode 角色code
     * @param state    工程师状态
     * @return
     * @author xiul
     * 2016-4-18 下午8:27:18
     * Description 第三方负责人分配工程师 dataGrid列表查询
     */
    private List<Map<String, Object>> queryForAreaEngineerByOrgCodeAndRoleCode(Map<String, String[]> paramsMap, String orgCode, String roleCode, List<String> authentications, String state) {
        StringBuffer sql = new StringBuffer ();
        sql.append ( " SELECT " );
        sql.append ( " eg.id, eg.`name`, eg.cellphone, eg.email, eg.state, eg.authentication" );
        sql.append ( " FROM  " );
        sql.append ( " t_s_base_user bu  " );
        sql.append ( " LEFT JOIN zy_engineer eg ON eg.ts_base_user_id = bu.ID  " );
        sql.append ( " LEFT JOIN t_s_user_org uo ON uo.user_id = bu.ID  " );
        sql.append ( " LEFT JOIN t_s_depart dp ON dp.ID = uo.org_id  " );
        sql.append ( " LEFT JOIN t_s_role_user ru ON ru.userid = bu.ID  " );
        sql.append ( " LEFT JOIN t_s_role ro ON ro.ID = ru.roleid  " );
        sql.append ( " WHERE  " );
        sql.append ( " dp.org_code LIKE '" ).append ( orgCode ).append ( "%' " );
        sql.append ( " AND dp.logic_delete = 0 " );
        sql.append ( " AND ro.rolecode = '" ).append ( roleCode ).append ( "' " );
        sql.append ( " AND eg.state = '" ).append ( state ).append ( "' " );
        sql.append ( " AND eg.is_delete = 0 " );
        sql.append ( "AND (" );
        for (int i = 0; i < authentications.size (); i++) {
            if (i == authentications.size () - 1) {
                sql.append ( " eg.authentication = '" ).append ( authentications.get ( i ) ).append ( "')" );
            } else {
                sql.append ( " eg.authentication = '" ).append ( authentications.get ( i ) ).append ( "' OR" );
            }
        }
        Integer page = 1, rows = 10;
        rows = Integer.valueOf ( null != paramsMap.get ( "rows" ) ? paramsMap.get ( "rows" )[0] : "0" );
        page = Integer.valueOf ( null != paramsMap.get ( "page" ) ? paramsMap.get ( "page" )[0] : "0" );
        if (StringUtil.isNotEmpty ( paramsMap.get ( "name" ) ) && StringUtil.isNotEmpty ( paramsMap.get ( "name" )[0] )) {
            sql.append ( " AND eg.name LIKE '%" ).append ( paramsMap.get ( "name" )[0].toString () ).append ( "%' " );
        }
        if (StringUtil.isNotEmpty ( paramsMap.get ( "cellphone" ) ) && StringUtil.isNotEmpty ( paramsMap.get ( "cellphone" )[0] )) {
            sql.append ( " AND eg.cellphone LIKE '%" ).append ( paramsMap.get ( "cellphone" )[0].toString () ).append ( "%' " );
        }
        if (StringUtil.isNotEmpty ( paramsMap.get ( "email" ) ) && StringUtil.isNotEmpty ( paramsMap.get ( "email" )[0] )) {
            sql.append ( " AND eg.email LIKE '%" ).append ( paramsMap.get ( "email" )[0].toString () ).append ( "%' " );
        }
        if (rows == 0 || page == 0) {
            return findForJdbc ( sql.toString () );
        }
        return findForJdbc ( sql.toString (), page, rows );
    }

    public List<Map<String, Object>> queryDatagridResultForChooseEngineers(Map<String, String[]> paramsMap, String orgCode, String planIds) {
        Criteria c = getSession ().createCriteria ( ZyInspectionPlanEntity.class );
        c.add ( Restrictions.in ( "id", planIds.split ( "," ) ) );
        c.add ( Restrictions.eq ( "lightPath", StaticValue.DIC_LIGHT_PATH_02 ) );
        Integer size = c.list ().size ();
        List<String> authentication = new ArrayList<String> ();
        boolean thisCompanyHadAreaEg = false;
        if (size > 0) {
            authentication = zyCommonService.getEngineerAuthenticationsByLigthPath ( StaticValue.DIC_LIGHT_PATH_02 );
            thisCompanyHadAreaEg = zyCommonService.judgeCompanyHadAreaEnginee ( orgCode, StaticValue.DIC_LIGHT_PATH_02 );
        } else {
            authentication = zyCommonService.getEngineerAuthenticationsByLigthPath ( StaticValue.DIC_LIGHT_PATH_01 );
            thisCompanyHadAreaEg = zyCommonService.judgeCompanyHadAreaEnginee ( orgCode, StaticValue.DIC_LIGHT_PATH_01 );
        }
        String roleCode = "";
        if (thisCompanyHadAreaEg) {
            roleCode = StaticValue.RULE_CODE_AREA_ENGINEER;
        } else {
            roleCode = StaticValue.RULE_CODE_THIRDPARTY_ENGINEER;
        }
        return queryForAreaEngineerByOrgCodeAndRoleCode ( paramsMap, orgCode, roleCode, authentication, StaticValue.DIC_ENGINEER_STATE_ONJOB );
//        if (results == null || results.size() == 0) {
//            //没有区域工程师 roleCode 为 RULE_CODE_THIRDPARTY_ENGINEER
//            results = queryForAreaEngineerByOrgCodeAndRoleCode(paramsMap, orgCode, StaticValue.RULE_CODE_THIRDPARTY_ENGINEER, authentication, StaticValue.DIC_ENGINEER_STATE_ONJOB);
//        }
//        return results;
    }

    public AjaxJson doBatchAssignEngineer(String planIds, ZyInspectionPlanEntity zyinpInspectionPlanEntity) {
        //这里的planId 是 巡检计划 主键ID
        AjaxJson j = new AjaxJson ();
        String message = "提交成功";
        boolean flag = true;
        try {
            if (StringUtil.isNotEmpty ( planIds )) {
                String[] planIdArr = planIds.split ( "," );
                if (planIdArr != null && planIdArr.length > 0) {
                    ZyEngineerEntity engineer = new ZyEngineerEntity ();
                    TSUser user = null;
                    for (String id : planIdArr) {
                        ZyInspectionPlanEntity zyIP = get ( ZyInspectionPlanEntity.class, id );
                        zyIP.setOrderBeginTime ( zyinpInspectionPlanEntity.getOrderBeginTime () );
                        zyIP.setOrderEndTime ( zyinpInspectionPlanEntity.getOrderEndTime () );
                        engineer = engineer != null ? get ( ZyEngineerEntity.class, zyinpInspectionPlanEntity.getEngineer ().getId () ) : engineer;
                        if (engineer.getIsAreaEngineer ()) {//如果是区域工程师，这里需要存上区域工程师
                            zyIP.setAreaEngineer ( engineer );
                        } else {//否则 存上 工程师
                            zyIP.setEngineer ( engineer );
                        }
                        zyIP.setState ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED );
                        List<String> authentication = zyCommonService.getEngineerAuthenticationsByLigthPath ( zyIP.getLightPath () );
                        List<Map<String, Object>> rsList = this.queryForAreaEngineers ( zyIP.getCompany (), StaticValue.RULE_CODE_AREA_ENGINEER, authentication, StaticValue.DIC_ENGINEER_STATE_ONJOB );
                        String approveFlag = "1";//默认流程走向是 1 工程师
                        //如果有区域工程师 走向为 3
                        if (rsList != null && rsList.size () > 0) {
                            approveFlag = "3";
                        }
                        TSBaseUser baseUser = systemService.get ( TSBaseUser.class, engineer.getTsBaseUser ().getId () );
//						Map<String, Object> returnMap = zyWorkFlowService.processComplete(ResourceUtil.getSessionUserName().getUserName(),"1", zyIP.getProcesssId(),baseUser.getUserName(), approveFlag,"userId");
                        /**-----------update by xiu  签收人采用assign webService调用时候没有session----------*/
//                        Map<String, Object> returnMap = zyWorkFlowService.processComplete ( "1", zyIP.getProcesssId (), baseUser.getUserName (), approveFlag, "userId" );
                        /**---------------------*/
                        this.saveOrUpdate ( zyIP );

//                        user = systemService.findUniqueByProperty ( TSUser.class, "userName", "admin" );//webService调用时 没有session 取不到值
                        user = ResourceUtil.getSessionUserName (); //当前用户
                        String userName = "";
                        String realName = "";
                        if(null!=user){
                            userName=user.getRealName ();
                            realName = user.getRealName ();
                        }else{
                            if(null!=zyIP.getContacter ()){
                                userName = zyIP.getContacter ().getTsBaseUser ().getUserName ();
                                realName = zyIP.getContacter ().getTsBaseUser ().getRealName ();
                            }
                        }

                        //保存巡检计划流程记录
                        ZyPlanRecordEntity zyPlanRecord = new ZyPlanRecordEntity ();
                        zyPlanRecord.setBusId ( zyIP.getId () );
                        zyPlanRecord.setPlanState ( zyIP.getState () );
                        zyPlanRecord.setProcInsId ( zyIP.getProcesssId () );
                        zyPlanRecord.setTaskId ( "" );
                        zyPlanRecord.setRemark ( "第三方负责人分配工程师：" + baseUser.getRealName () );
                        zyPlanRecord.setCreateDate ( new Date () );//webService调用时 没有session 取不到值
                        zyPlanRecord.setCreateBy ( userName);//webService调用时 没有session 取不到值
                        zyPlanRecord.setCreateName ( realName );//webService调用时 没有session 取不到值
                        systemService.save ( zyPlanRecord );
                    }
                    //发送短信
                    Map<String, Object> paraMap = new HashMap<String, Object> ();
                    paraMap.put ( "engineerName", engineer.getName () );
                    paraMap.put ( "planTaskCount", planIdArr.length );
                    SendMessage.sendSMSFTL ( engineer.getCellphone (), "message_tpSendToEngineer.ftl", paraMap, systemService );
                    //创建 APP消息
                    CbsAppMessageEntity appMessage = new CbsAppMessageEntity ();
                    String content = "您收到" + planIds.split ( "," ).length + "个新的巡检任务，可在“我的任务”中查看详情。";
                    appMessage.setContent ( content );
                    appMessage.setSender ( user.getId () );
                    TSBaseUser baseUser = systemService.get ( TSBaseUser.class, engineer.getTsBaseUser ().getId () );
                    appMessage.setReciver ( baseUser.getId () );
                    appMessage.setState ( StaticValue.DIC_APP_MESSAGE_STATE_UNREAD );
                    systemService.save ( appMessage );
                    systemService.addLog ( "新增APP消息,接受方:" + baseUser.getId () + ",内容:" + content, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL );
                }
            }
        } catch (Exception e) {
            message = "提交失败";
            flag = false;
        }
        j.setSuccess ( flag );
        j.setMsg ( message );
        return j;
    }

    public AjaxJson doBatchAssignEngineerCurrentUser(String planIds, ZyInspectionPlanEntity zyinpInspectionPlanEntity) {
        //这里的planId 是 巡检计划 主键ID
        AjaxJson j = new AjaxJson ();
        String message = "提交成功";
        boolean flag = true;
        try {
            if (StringUtil.isNotEmpty ( planIds )) {
                String[] planIdArr = planIds.split ( "," );
                if (planIdArr != null && planIdArr.length > 0) {
                    ZyEngineerEntity engineer = new ZyEngineerEntity ();
                    TSUser user = null;
                    for (String id : planIdArr) {
                        ZyInspectionPlanEntity zyIP = get ( ZyInspectionPlanEntity.class, id );
                        zyIP.setOrderBeginTime ( zyinpInspectionPlanEntity.getOrderBeginTime () );
                        zyIP.setOrderEndTime ( zyinpInspectionPlanEntity.getOrderEndTime () );
                        engineer = engineer != null ? get ( ZyEngineerEntity.class, zyinpInspectionPlanEntity.getEngineer ().getId () ) : engineer;
                        if (engineer.getIsAreaEngineer ()) {//如果是区域工程师，这里需要存上区域工程师
                            zyIP.setAreaEngineer ( engineer );
                        } else {//否则 存上 工程师
                            zyIP.setEngineer ( engineer );
                        }
                        zyIP.setState ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED );
                        List<String> authentication = zyCommonService.getEngineerAuthenticationsByLigthPath ( zyIP.getLightPath () );
                        List<Map<String, Object>> rsList = this.queryForAreaEngineers ( zyIP.getCompany (), StaticValue.RULE_CODE_AREA_ENGINEER, authentication, StaticValue.DIC_ENGINEER_STATE_ONJOB );
//                        String approveFlag = "1";//默认流程走向是 1 工程师
//                        //如果有区域工程师 走向为 3
//                        if (rsList != null && rsList.size () > 0) {
//                            approveFlag = "3";
//                        }
                        TSBaseUser baseUser = systemService.get ( TSBaseUser.class, engineer.getTsBaseUser ().getId () );
//						Map<String, Object> returnMap = zyWorkFlowService.processComplete(ResourceUtil.getSessionUserName().getUserName(),"1", zyIP.getProcesssId(),baseUser.getUserName(), approveFlag,"userId");
                        /**-----------update by xiu  签收人采用assign webService调用时候没有session----------*/
//                        Map<String, Object> returnMap = zyWorkFlowService.processComplete ( "1", zyIP.getProcesssId (), baseUser.getUserName (), "2", "userId" );
                        /**---------------------*/


//                        List htis = historyService.createHistoricTaskInstanceQuery().processInstanceId(zyIP.getProcesssId ()).list();
//                        List<HistoricTaskInstance> hisTasks = historyService.createHistoricTaskInstanceQuery ().finished ().processInstanceId ( zyIP.getProcesssId () ).orderByHistoricTaskInstanceStartTime ().desc ().list ();
//                        Set set = new HashSet (  );
//                        //判断并保存设置不可见巡检计划人
//                        for (int i = 0; i < hisTasks.size (); i++) {
//                            HistoricTaskInstance historicTaskInstance = hisTasks.get ( i );
//                            if(historicTaskInstance.getTaskDefinitionKey ().equals ( "taskNode03-1" )||historicTaskInstance.getTaskDefinitionKey ().equals ( "taskNode03-2" )){
//                                String userName = historicTaskInstance.getAssignee ();
//                                set.add ( userName );
//                            }
//                        }
//                        if(set.size ()>0){
//                            zyIP.setReTurnPeople(set.toString ());
//                        }
                        this.saveOrUpdate ( zyIP );

//                        user = systemService.findUniqueByProperty ( TSUser.class, "userName", "admin" );//webService调用时 没有session 取不到值
                        TSBaseUser user1 = ResourceUtil.getSessionUserName (); //当前用户

                        //保存巡检计划流程记录
                        ZyPlanRecordEntity zyPlanRecord = new ZyPlanRecordEntity ();
                        zyPlanRecord.setBusId ( zyIP.getId () );
                        zyPlanRecord.setPlanState ( zyIP.getState () );
                        zyPlanRecord.setProcInsId ( zyIP.getProcesssId () );
                        zyPlanRecord.setTaskId ( "" );
                        zyPlanRecord.setRemark ( "第三方负责人分配工程师：" + baseUser.getRealName () );
                        zyPlanRecord.setCreateDate ( new Date () );//webService调用时 没有session 取不到值
                        zyPlanRecord.setCreateBy ( null!=user1?user1.getUserName ():"" );//webService调用时 没有session 取不到值
                        zyPlanRecord.setCreateName (  null!=user1?user1.getRealName ():"" );//webService调用时 没有session 取不到值
                        systemService.save ( zyPlanRecord );
                    }
                    //发送短信
                    Map<String, Object> paraMap = new HashMap<String, Object> ();
                    paraMap.put ( "engineerName", engineer.getName () );
                    paraMap.put ( "planTaskCount", planIdArr.length );
                    SendMessage.sendSMSFTL ( engineer.getCellphone (), "message_tpSendToEngineer.ftl", paraMap, systemService );
                    //创建 APP消息
                    CbsAppMessageEntity appMessage = new CbsAppMessageEntity ();
                    String content = "您收到" + planIds.split ( "," ).length + "个新的巡检任务，可在“我的任务”中查看详情。";
                    appMessage.setContent ( content );
                    appMessage.setSender ( user.getId () );
                    TSBaseUser baseUser = systemService.get ( TSBaseUser.class, engineer.getTsBaseUser ().getId () );
                    appMessage.setReciver ( baseUser.getId () );
                    appMessage.setState ( StaticValue.DIC_APP_MESSAGE_STATE_UNREAD );
                    systemService.save ( appMessage );
                    systemService.addLog ( "新增APP消息,接受方:" + baseUser.getId () + ",内容:" + content, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL );
                }
            }
        } catch (Exception e) {
            message = "提交失败";
            flag = false;
        }
        j.setSuccess ( flag );
        j.setMsg ( message );
        return j;
    }


    /**
     * @param id                        巡检计划ID
     * @param zyinpInspectionPlanEntity 包含 工程师，预约时间起止时间
     * @return
     */
    public AjaxJson doBatchAssignEngineers(String id,String engineerName,ZyInspectionPlanEntity zyinpInspectionPlanEntity) {
        //这里的planId 是 巡检计划 主键ID
        AjaxJson j = new AjaxJson ();
//        String stateOld = ""; //转派前的巡检计划状态
        String message = "提交成功";
        boolean flag = true;
        TSBaseUser user1 = ResourceUtil.getSessionUserName ();
        try {
            //找到该条巡检计划
            ZyInspectionPlanEntity zyIP = get ( ZyInspectionPlanEntity.class, id );

            List<ZyEngineerEntity> zyEngineerEntity = systemService.findByProperty ( ZyEngineerEntity.class,"name",engineerName );

            //查看工程师是区域工程师还是只是工程师
            if(zyEngineerEntity.size ()>0){
                //是区域工程师
                if(zyEngineerEntity.get ( 0 ).getIsAreaEngineer ()){
                    zyIP.setEngineer (null);
                    zyIP.setAreaEngineer ( zyEngineerEntity.get ( 0 ) );
                }else{
                    zyIP.setEngineer (zyEngineerEntity.get ( 0 ));
                    zyIP.setAreaEngineer ( null );
                }
            }
            zyIP.setState ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED );
            this.saveOrUpdate ( zyIP );

//            Task task = taskService.createTaskQuery().processInstanceId(zyIP.getProcesssId ()).active().singleResult();

            //保存巡检计划流程记录
            ZyPlanRecordEntity zyPlanRecord = new ZyPlanRecordEntity ();
            zyPlanRecord.setBusId ( zyIP.getId () );
            zyPlanRecord.setPlanState ( zyIP.getState () );
            zyPlanRecord.setProcInsId ( zyIP.getProcesssId () );
            zyPlanRecord.setTaskId ( null);
            zyPlanRecord.setRemark ( "第三方负责人分配工程师：" + engineerName );
            zyPlanRecord.setCreateDate ( new Date () );//webService调用时 没有session 取不到值
            zyPlanRecord.setCreateBy ( user1.getUserName () );//webService调用时 没有session 取不到值
            zyPlanRecord.setCreateName ( user1.getRealName () );//webService调用时 没有session 取不到值
            systemService.save ( zyPlanRecord );


            //发送短信
            Map<String, Object> paraMap = new HashMap<String, Object> ();
            paraMap.put ( "engineerName",null!=zyIP.getEngineer ()?zyIP.getEngineer ().getName ():(null!=zyIP.getAreaEngineer ()?zyIP.getAreaEngineer ().getName ():"") );
            paraMap.put ( "planTaskCount", "1" );
            SendMessage.sendSMSFTL (null!=zyIP.getEngineer ()?zyIP.getEngineer ().getCellphone ():(null!=zyIP.getAreaEngineer ()?zyIP.getAreaEngineer ().getCellphone ():"") , "message_tpSendToEngineer.ftl", paraMap, systemService );
            //创建 APP消息
            CbsAppMessageEntity appMessage = new CbsAppMessageEntity ();
            String content = "您收到1个新的巡检任务，可在“我的任务”中查看详情。";
            appMessage.setContent ( content );
            appMessage.setSender ( user1.getId () );
            TSBaseUser baseUser = systemService.get ( TSBaseUser.class, null!=zyIP.getEngineer ()?zyIP.getEngineer ().getTsBaseUser ().getId (): (null!=zyIP.getAreaEngineer ()? zyIP.getAreaEngineer ().getTsBaseUser ().getId ():"" ));
            appMessage.setReciver ( baseUser.getId () );
            appMessage.setState ( StaticValue.DIC_APP_MESSAGE_STATE_UNREAD );
            systemService.save ( appMessage );
            systemService.addLog ( "新增APP消息,接受方:" + zyIP.getContacter ().getTsBaseUser ().getId () + ",内容:" + content, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL );

        } catch (Exception e) {
            message = "提交失败";
            flag = false;
        }
        j.setSuccess ( flag );
        j.setMsg ( message );
        return j;
    }


    //这里的planId 是 巡检计划 主键ID
    public String doBatchRefuseMission(String planIds, String remark, String fileId) {
        String message = "拒单成功";
        try {
            String[] idsArr = planIds.split ( "," );
            if (idsArr != null && idsArr.length > 0) {
                for (int i = 0; i < idsArr.length; i++) {
                    ZyInspectionPlanEntity zyIP = get ( ZyInspectionPlanEntity.class, idsArr[i] );
                    zyIP.setState ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_REFUSED );
//                    Map<String, Object> returnMap = zyWorkFlowService.processComplete ( "1", zyIP.getProcesssId (), "", "2", "userId" );
//                    zyIP.setEngineer ( null );
//                    zyIP.setAreaEngineer ( null );
//                    zyIP.setContacter ( null );
                    this.saveOrUpdate ( zyIP );
                    TSBaseUser user1 = ResourceUtil.getSessionUserName (); //当前用户
                    //保存巡检计划流程记录
                    ZyPlanRecordEntity zyPlanRecord = new ZyPlanRecordEntity ();
                    zyPlanRecord.setBusId ( zyIP.getId () );
                    zyPlanRecord.setPlanState ( zyIP.getState () );
                    zyPlanRecord.setProcInsId ( zyIP.getProcesssId () );
                    zyPlanRecord.setTaskId ( "" );
                    zyPlanRecord.setRemark ( "第三方负责人拒绝任务，拒绝原因：" + remark );
                    zyPlanRecord.setCreateDate ( new Date () );//webService调用时 没有session 取不到值
                    zyPlanRecord.setCreateBy ( null != user1 ? user1.getUserName () : null );//webService调用时 没有session 取不到值
                    zyPlanRecord.setCreateName ( null != user1? user1.getRealName () : null );//webService调用时 没有session 取不到值
//                    zyPlanRecord.setFileId ( fileId );
                    systemService.save ( zyPlanRecord );

                    if(StringUtil.isNotEmpty ( fileId )){
                        if(i==0){
                            //获取上传附件信息
                            ZyFileLogEntity zyFileLogEntity = systemService.get ( ZyFileLogEntity.class, fileId);
                            zyFileLogEntity.setBusinessKey ( zyPlanRecord.getId () );
                            systemService.saveOrUpdate ( zyFileLogEntity );
                        }else{
                            ZyFileLogEntity zyFileLogEntity = systemService.get ( ZyFileLogEntity.class, fileId);

                            ZyFileLogEntity zyFileLogEntity1 = new ZyFileLogEntity ();
                            zyFileLogEntity1.setCreateBy ( zyFileLogEntity.getCreateBy () );
                            zyFileLogEntity1.setCreateDate ( zyFileLogEntity.getCreateDate () );
                            zyFileLogEntity1.setOldFileName ( zyFileLogEntity.getOldFileName () );
                            zyFileLogEntity1.setFilePath ( zyFileLogEntity.getFilePath () );
                            zyFileLogEntity1.setFileType ( zyFileLogEntity.getFileType () );
                            zyFileLogEntity1.setNewFileName ( zyFileLogEntity.getNewFileName () );
                            zyFileLogEntity1.setBusinessKey ( zyPlanRecord.getId () );
                            systemService.saveOrUpdate ( zyFileLogEntity1 );
                        }

                    }
                }
            }
        } catch (Exception e) {
            message = "拒绝失败";
            e.printStackTrace ();
        }
        return message;
    }

    @Override
    public void queryDatagridResultForAreaChooseEngineers(HttpServletRequest request, DataGrid dataGrid, String orgCode, String planIds) {
        Criteria c = getSession ().createCriteria ( ZyInspectionPlanEntity.class );
        c.add ( Restrictions.in ( "id", planIds.split ( "," ) ) );
        c.add ( Restrictions.eq ( "lightPath", StaticValue.DIC_LIGHT_PATH_02 ) );
        Integer size = c.list ().size ();
        List<String> autthentications = new ArrayList<String> ();
        if (size > 0) {
            autthentications = zyCommonService.getEngineerAuthenticationsByLigthPath ( StaticValue.DIC_LIGHT_PATH_02 );
        } else {
            autthentications = zyCommonService.getEngineerAuthenticationsByLigthPath ( StaticValue.DIC_LIGHT_PATH_01 );
        }
        TSUser user = ResourceUtil.getSessionUserName ();
        StringBuffer sql = new StringBuffer ();
        sql.append ( " SELECT " );
        sql.append ( " eg.id, eg.`name`, eg.cellphone, eg.email, eg.state " );
        sql.append ( " FROM " );
        sql.append ( " t_s_base_user bu " );
        sql.append ( " LEFT JOIN zy_engineer eg on eg.ts_base_user_id = bu.ID " );
        sql.append ( " LEFT JOIN t_s_user_org uo on uo.user_id = bu.ID " );
        sql.append ( " LEFT JOIN t_s_depart dp on dp.ID = uo.org_id " );
        sql.append ( " LEFT JOIN t_s_role_user ru on ru.userid = bu.ID " );
        sql.append ( " LEFT JOIN t_s_role ro on ro.ID = ru.roleid " );
        sql.append ( " WHERE " );
        sql.append ( " eg.ts_base_user_id = '" ).append ( user.getId () ).append ( "' " );//区域工程师可以分配给自己任务，所以这里根据当前用户（当前登录的是区域工程师）查询出自己
        sql.append ( " AND eg.is_delete = '0' " );//只查询未逻辑删除的
        sql.append ( " AND ( " );
        for (int i = 0; i < autthentications.size (); i++) {
            if (autthentications.get ( i ) != null && StringUtil.isNotEmpty ( autthentications.get ( i ) )) {
                if (i == autthentications.size () - 1) {
                    sql.append ( " eg.authentication = '" ).append ( autthentications.get ( i ) ).append ( "')" );
                } else {
                    sql.append ( " eg.authentication = '" ).append ( autthentications.get ( i ) ).append ( "' OR" );
                }
            }
        }
        appendSqlParameter ( sql, request );
        sql.append ( " UNION " );
        sql.append ( " SELECT " );
        sql.append ( " eg.id, eg.`name`, eg.cellphone, eg.email, eg.state " );
        sql.append ( " FROM " );
        sql.append ( " t_s_base_user bu " );
        sql.append ( " LEFT JOIN zy_engineer eg on eg.ts_base_user_id = bu.ID " );
        sql.append ( " LEFT JOIN zy_engineer peg on peg.id = eg.parent_id " );
        sql.append ( " LEFT JOIN t_s_user_org uo on uo.user_id = bu.ID " );
        sql.append ( " LEFT JOIN t_s_depart dp on dp.ID = uo.org_id " );
        sql.append ( " LEFT JOIN t_s_role_user ru on ru.userid = bu.ID " );
        sql.append ( " LEFT JOIN t_s_role ro on ro.ID = ru.roleid " );
        sql.append ( " WHERE " );
        sql.append ( " peg.ts_base_user_id = '" ).append ( user.getId () ).append ( "' " );//父级工程师 的 关联用户表的ID必须是 当前用户（当前登录的是区域工程师）。基础条件
        sql.append ( " AND dp.org_code LIKE '" ).append ( orgCode ).append ( "%' " );//组织机构
        sql.append ( " AND dp.logic_delete = 0 " );
        sql.append ( " AND ( " );
        sql.append ( " ro.rolecode = '" ).append ( StaticValue.RULE_CODE_THIRDPARTY_ENGINEER ).append ( "' " );//两种角色都可以指派
        sql.append ( " OR " );
        sql.append ( " ro.rolecode = '" ).append ( StaticValue.RULE_CODE_AREA_ENGINEER ).append ( "' " );//两种角色都可以指派
        sql.append ( " ) " );
        sql.append ( " AND eg.state = '" ).append ( StaticValue.DIC_ENGINEER_STATE_ONJOB ).append ( "' " );//在职
        sql.append ( " AND eg.is_delete = '0' " );//只查询未逻辑删除的
        sql.append ( " AND ( " );
        for (int i = 0; i < autthentications.size (); i++) {
            if (autthentications.get ( i ) != null && StringUtil.isNotEmpty ( autthentications.get ( i ) )) {
                if (i == autthentications.size () - 1) {
                    sql.append ( " eg.authentication = '" ).append ( autthentications.get ( i ) ).append ( "')" );
                } else {
                    sql.append ( " eg.authentication = '" ).append ( autthentications.get ( i ) ).append ( "' OR" );
                }
            }
        }
        appendSqlParameter ( sql, request );
        Map<String, String[]> paramsMap = request.getParameterMap ();
        int totalCount = 0;
        Integer page = 1, rows = 10;
        rows = Integer.valueOf ( null != paramsMap.get ( "rows" ) ? paramsMap.get ( "rows" )[0] : "0" );
        page = Integer.valueOf ( null != paramsMap.get ( "page" ) ? paramsMap.get ( "page" )[0] : "0" );
        List<Map<String, Object>> rsMapList = new ArrayList<Map<String, Object>> ();
        if (rows == 0 && page == 0) {
            rsMapList = findForJdbc ( sql.toString () );
        } else {
            dataGrid.setPage ( page );
            dataGrid.setRows ( rows );
            rsMapList = findForJdbc ( sql.toString (), page, rows );
        }
        List<Map<String, Object>> countMapList = super.findForJdbc ( sql.toString () );
        if (null != countMapList && countMapList.size () > 0) {
            totalCount = countMapList.size ();
        }
        dataGrid.setTotal ( totalCount );
        dataGrid.setResults ( rsMapList );
    }

    /**
     * 区域工程师拒单
     * @param planIds
     * @param remark
     * @return
     */
    public String doBatchRefuseMissionOfAreaEngineer(String planIds, String remark,String fileId) {
        String message = "拒单成功";
        try {
            if (StringUtil.isNotEmpty ( planIds )) {
                String[] planIdArr = planIds.split ( "," );
                if (planIdArr != null && planIdArr.length > 0) {
                    for (int i = 0; i < planIdArr.length; i++) {
                        ZyInspectionPlanEntity zyIP = get ( ZyInspectionPlanEntity.class, planIdArr[i] );
                        zyIP.setState ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_REFUSED );
                        zyIP.setEngineer ( null );
                        zyIP.setAreaEngineer ( null );
                        this.saveOrUpdate ( zyIP );
                        TSBaseUser user1 = ResourceUtil.getSessionUserName (); //当前用户

                        //保存巡检计划流程记录
                        ZyPlanRecordEntity zyPlanRecord = new ZyPlanRecordEntity ();
                        zyPlanRecord.setBusId ( zyIP.getId () );
                        zyPlanRecord.setPlanState ( zyIP.getState () );
                        zyPlanRecord.setProcInsId ( zyIP.getProcesssId () );
                        zyPlanRecord.setTaskId ( "" );
                        zyPlanRecord.setRemark ( "区域工程师拒绝任务，拒绝原因：" + remark );
                        zyPlanRecord.setCreateDate ( new Date () );//webService调用时 没有session 取不到值
                        zyPlanRecord.setCreateBy ( null != user1 ? user1.getUserName () : null );//webService调用时 没有session 取不到值
                        zyPlanRecord.setCreateName ( null != user1 ? user1.getRealName () : null );//webService调用时 没有session 取不到值
                        systemService.save ( zyPlanRecord );

                        if(StringUtil.isNotEmpty ( fileId )){
                            if(i==0){
                                //获取上传附件信息
                                ZyFileLogEntity zyFileLogEntity = systemService.get ( ZyFileLogEntity.class, fileId);
                                zyFileLogEntity.setBusinessKey ( zyPlanRecord.getId () );
                                systemService.saveOrUpdate ( zyFileLogEntity );
                            }else{
                                ZyFileLogEntity zyFileLogEntity = systemService.get ( ZyFileLogEntity.class, fileId);

                                ZyFileLogEntity zyFileLogEntity1 = new ZyFileLogEntity ();
                                zyFileLogEntity1.setCreateBy ( zyFileLogEntity.getCreateBy () );
                                zyFileLogEntity1.setCreateDate ( zyFileLogEntity.getCreateDate () );
                                zyFileLogEntity1.setOldFileName ( zyFileLogEntity.getOldFileName () );
                                zyFileLogEntity1.setFilePath ( zyFileLogEntity.getFilePath () );
                                zyFileLogEntity1.setFileType ( zyFileLogEntity.getFileType () );
                                zyFileLogEntity1.setNewFileName ( zyFileLogEntity.getNewFileName () );
                                zyFileLogEntity1.setBusinessKey ( zyPlanRecord.getId () );
                                systemService.saveOrUpdate ( zyFileLogEntity1 );
                            }

                        }
                    }
                }
            }
        } catch (Exception e) {
            message = "拒单失败";
            e.printStackTrace ();
        }
        return message;
    }

    /**
     * 工程师拒单
     */
    public String doBatchRefuseMissionOfEngineer(String planIds, String remark,String fileId) {
        //这里的planId 是 巡检计划 主键ID
        String message = "拒单成功";
        try {
            String[] idsArr = planIds.split ( "," );
            if (idsArr != null && idsArr.length > 0) {
                for (int i = 0; i < idsArr.length; i++) {
                    ZyInspectionPlanEntity zyIP = get ( ZyInspectionPlanEntity.class, idsArr[i] );
                    zyIP.setState ( StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED );
                    zyIP.setEngineer ( null );
                    this.saveOrUpdate ( zyIP );
                    //查找当前用户
                    TSBaseUser user1 = ResourceUtil.getSessionUserName (); //当前用户
                    //保存巡检计划流程记录
                    ZyPlanRecordEntity zyPlanRecord = new ZyPlanRecordEntity ();
                    zyPlanRecord.setBusId ( zyIP.getId () );
                    zyPlanRecord.setPlanState ( zyIP.getState () );
                    zyPlanRecord.setProcInsId ( zyIP.getProcesssId () );
                    zyPlanRecord.setRemark ( "工程师拒绝任务，拒绝原因：" + remark );
                    zyPlanRecord.setTaskId ( "" );
                    zyPlanRecord.setCreateDate ( new Date () );//webService调用时 没有session 取不到值
                    zyPlanRecord.setCreateBy (null!=user1?user1.getUserName ():null );//webService调用时 没有session 取不到值
                    zyPlanRecord.setCreateName ( null!=user1?user1.getRealName ():null );//webService调用时 没有session 取不到值
                    systemService.save ( zyPlanRecord );

                    if(StringUtil.isNotEmpty ( fileId )){
                        if(i==0){
                            //获取上传附件信息
                            ZyFileLogEntity zyFileLogEntity = systemService.get ( ZyFileLogEntity.class, fileId);
                            zyFileLogEntity.setBusinessKey ( zyPlanRecord.getId () );
                            systemService.saveOrUpdate ( zyFileLogEntity );
                        }else{
                            ZyFileLogEntity zyFileLogEntity = systemService.get ( ZyFileLogEntity.class, fileId);

                            ZyFileLogEntity zyFileLogEntity1 = new ZyFileLogEntity ();
                            zyFileLogEntity1.setCreateBy ( zyFileLogEntity.getCreateBy () );
                            zyFileLogEntity1.setCreateDate ( zyFileLogEntity.getCreateDate () );
                            zyFileLogEntity1.setOldFileName ( zyFileLogEntity.getOldFileName () );
                            zyFileLogEntity1.setFilePath ( zyFileLogEntity.getFilePath () );
                            zyFileLogEntity1.setFileType ( zyFileLogEntity.getFileType () );
                            zyFileLogEntity1.setNewFileName ( zyFileLogEntity.getNewFileName () );
                            zyFileLogEntity1.setBusinessKey ( zyPlanRecord.getId () );
                            systemService.saveOrUpdate ( zyFileLogEntity1 );
                        }

                    }

                }
            }
        } catch (Exception e) {
            message = "拒单失败";
            e.printStackTrace ();
        }
        return message;
    }


    public void doBatchEngineerAssignPlan(String planIds) {
        //这里的planId 是 巡检计划 主键ID
        if (StringUtil.isNotEmpty ( planIds )) {
            String[] planIdArr = planIds.split ( "," );
            if (planIdArr != null && planIdArr.length > 0) {
                for (String id : planIdArr) {
                    ZyInspectionPlanEntity zyIP = get ( ZyInspectionPlanEntity.class, id );
                    zyIP.setState ( StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED );
//                    Map<String, Object> returnMap = zyWorkFlowService.processComplete ( "1", zyIP.getProcesssId (), zyIP.getEngineer ().getTsBaseUser ().getUserName (), "1", "userId" );
                    this.saveOrUpdate ( zyIP );
                    //查找当前用户
                    TSBaseUser user1 = ResourceUtil.getSessionUserName (); //当前用户
                    //保存巡检计划流程记录
                    ZyPlanRecordEntity zyPlanRecord = new ZyPlanRecordEntity ();
                    zyPlanRecord.setBusId ( zyIP.getId () );
                    zyPlanRecord.setPlanState ( zyIP.getState () );
                    zyPlanRecord.setProcInsId ( zyIP.getProcesssId () );
                    zyPlanRecord.setTaskId ( "" );
                    zyPlanRecord.setRemark ( "工程师接受任务" );
                    zyPlanRecord.setCreateDate ( new Date () );//webService调用时 没有session 取不到值
                    zyPlanRecord.setCreateBy ( null != user1 ? user1.getUserName () : null );//webService调用时 没有session 取不到值
                    zyPlanRecord.setCreateName ( null != user1 ? user1.getRealName () : null );//webService调用时 没有session 取不到值
                    systemService.save ( zyPlanRecord );
                }
            }
        }
    }

    /**
     * @param sql
     * @author xiul
     * 2016-4-19 下午2:38:59
     * Description 拼接查询条件 for  queryDatagridResultForAreaChooseEngineers
     */
    private void appendSqlParameter(StringBuffer sql, HttpServletRequest request) {
        Map<String, String[]> paramsMap = request.getParameterMap ();
        if (StringUtil.isNotEmpty ( paramsMap.get ( "name" ) ) && StringUtil.isNotEmpty ( paramsMap.get ( "name" )[0] )) {
            sql.append ( " AND eg.name LIKE '%" ).append ( paramsMap.get ( "name" )[0].toString () ).append ( "%' " );
        }
        if (StringUtil.isNotEmpty ( paramsMap.get ( "cellphone" ) ) && StringUtil.isNotEmpty ( paramsMap.get ( "cellphone" )[0] )) {
            sql.append ( " AND eg.cellphone LIKE '%" ).append ( paramsMap.get ( "cellphone" )[0].toString () ).append ( "%' " );
        }
        if (StringUtil.isNotEmpty ( paramsMap.get ( "email" ) ) && StringUtil.isNotEmpty ( paramsMap.get ( "email" )[0] )) {
            sql.append ( " AND eg.email LIKE '%" ).append ( paramsMap.get ( "email" )[0].toString () ).append ( "%' " );
        }
    }

    public void doBatchAreaAssignEngineer(String planIds, String engineerId, String orderBeginTimeStr, String orderEndTimeStr) {
        try {
            Date orderBeginTime = DateUtils.str2Date ( orderBeginTimeStr, DateUtils.date_sdf );
            Date orderEndTime = DateUtils.str2Date ( orderEndTimeStr, DateUtils.date_sdf );
            ZyEngineerEntity engineer = super.get ( ZyEngineerEntity.class, engineerId );
            TSBaseUser tsBaseUser = null;
            if (null != engineer) {
                tsBaseUser = super.get ( TSBaseUser.class, engineer.getTsBaseUser ().getId () );
            }
            if (StringUtil.isNotEmpty ( planIds )) {
                String[] planIdArr = planIds.split ( "," );
                if (planIdArr != null && planIdArr.length > 0) {
                    TSUser user = null;
                    for (String id : planIdArr) {
                        ZyInspectionPlanEntity zyIP = get ( ZyInspectionPlanEntity.class, id );
                        if (null != orderBeginTime && null != orderEndTime) {
                            zyIP.setOrderBeginTime ( orderBeginTime );
                            zyIP.setOrderEndTime ( orderEndTime );
                        }
                        zyIP.setState ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_ASSIGNED );//状态变为 区域工程师已分配
                        if (null == tsBaseUser) {
                            break;
                        }
//                        Map<String, Object> returnMap = zyWorkFlowService.processComplete ( "1", zyIP.getProcesssId (), tsBaseUser.getUserName (), "1", "userId" );
                        zyIP.setEngineer ( engineer );
                        this.saveOrUpdate ( zyIP );
//                        user = systemService.findUniqueByProperty ( TSUser.class, "userName", "admin" );//webService调用时 没有session 取不到值
                        user = ResourceUtil.getSessionUserName (); //当前用户
                        //保存巡检计划流程记录
                        ZyPlanRecordEntity zyPlanRecord = new ZyPlanRecordEntity ();
                        zyPlanRecord.setBusId ( zyIP.getId () );
                        zyPlanRecord.setPlanState ( zyIP.getState () );
                        zyPlanRecord.setProcInsId ( zyIP.getProcesssId () );
                        zyPlanRecord.setTaskId ( "" );
                        zyPlanRecord.setRemark ( "区域工程师分派任务给[" + engineer.getName () + "]" );
                        zyPlanRecord.setCreateDate ( new Date () );//webService调用时 没有session 取不到值
                        zyPlanRecord.setCreateBy (null!=user?user.getUserName ():"" );//webService调用时 没有session 取不到值
                        zyPlanRecord.setCreateName ( null!=user?user.getRealName ():"" );//webService调用时 没有session 取不到值
                        systemService.save ( zyPlanRecord );
                    }
//                    //发送邮件
//                    ZyEmailEntity eMail = new ZyEmailEntity();
//                    eMail.setEmailSubject("巴可巡检任务分派通知");
//                    eMail.setEmailReceiver(zyEngineer.getEmail());
//                    Map<String, Object> paraMap = new HashMap<String, Object>();
//                    paraMap.put("tpHeaderName", zyEngineer.getName());
//                    paraMap.put("url", StaticValue.HTTP_HEADER);
//                    paraMap.put("planTaskCount", planIdArr.length);
//                    SendMailUtil.sendFtlMail(eMail, "mail_aegSendToEngineer.ftl", paraMap, systemService);
                    if (StringUtil.isNotEmpty ( engineer.getCellphone () )) {
                        //发送短信
                        Map<String, Object> paraMap = new HashMap<String, Object> ();
                        paraMap.put ( "engineerName", engineer.getName () );
                        paraMap.put ( "planTaskCount", planIdArr.length );
                        SendMessage.sendSMSFTL ( engineer.getCellphone (), "message_aegSendToEngineer.ftl", paraMap, systemService );
                    }
                    //创建 APP消息
                    CbsAppMessageEntity appMessage = new CbsAppMessageEntity ();
                    String content = "您收到" + planIds.split ( "," ).length + "个新的巡检任务，可在“我的任务”中查看详情。";
                    appMessage.setContent ( content );
                    appMessage.setSender ( user.getId () );
                    TSBaseUser baseUser = systemService.get ( TSBaseUser.class, engineer.getTsBaseUser ().getId () );
                    appMessage.setReciver ( baseUser.getId () );
                    appMessage.setState ( StaticValue.DIC_APP_MESSAGE_STATE_UNREAD );
                    systemService.save ( appMessage );
                    systemService.addLog ( "新增APP消息,接受方:" + baseUser.getId () + ",内容:" + content, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL );
                }
            }
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }

    @Override
    public void cancelInspectionPlan(ZyInspectionPlanEntity t, HttpServletRequest request) {
        String remark = oConvertUtils.getString ( request.getParameter ( "remark" ) );
        if (!t.getState ().equals ( StaticValue.DIC_PLAN_STATE_TODO )) {
            //待处理状态的巡检计划，并没有启动流程，所以不需要 endProcess
//            zyWorkFlowService.endProcess ( t.getId () );
        }
        ZyInspectionPlanEntity zyIp = get ( ZyInspectionPlanEntity.class, t.getId () );
        String beforeCancelState = zyIp.getState ();//保留取消巡检计划之前的状态
        zyIp.setState ( StaticValue.DIC_PLAN_STATE_INSPECTION_CANCEL );
        systemService.saveOrUpdate ( zyIp );
        ZyPlanRecordEntity zyPlanRecord = new ZyPlanRecordEntity ();
        zyPlanRecord.setBusId ( zyIp.getId () );
        zyPlanRecord.setPlanState ( zyIp.getState () );
        zyPlanRecord.setProcInsId ( zyIp.getProcesssId () );
        zyPlanRecord.setRemark ( "取消巡检计划，备注：" + remark );
        systemService.save ( zyPlanRecord );
        ZyEquipmentSpareEntity zyEs = super.getEntity ( ZyEquipmentSpareEntity.class, zyIp.getEquipmentSpare ().getId () );
        zyEs.setIsHadInspection ( "0" );
        Integer resudualIpCount = zyEs.getResidualIpCount ();
        zyEs.setResidualIpCount ( ++resudualIpCount );
        super.saveOrUpdate ( zyEs );//20160712 amy提出 需要在生成巡检计划列表 是否有本年度巡检计划 为 否的时候查询到取消的巡检计划

        /**--发邮件 && APP消息--*/
        TSUser user = ResourceUtil.getSessionUserName ();
        //第三方联系人不为空，并且不是待处理状态（待处理状态联系人有值）
        if (zyIp.getContacter () != null && StringUtil.isNotEmpty ( zyIp.getContacter ().getId () ) && !beforeCancelState.equals ( StaticValue.DIC_PLAN_STATE_TODO )) {//
            if (StringUtil.isNotEmpty ( zyIp.getContacter ().getEmail () )) {
                try {
                    //发送邮件
                    ZyEmailEntity eMail = new ZyEmailEntity ();
                    eMail.setEmailSubject ( "巴可巡检任务取消通知" );
                    eMail.setEmailReceiver ( zyIp.getContacter ().getEmail () );
                    Map<String, Object> paraMap = new HashMap<String, Object> ();
                    paraMap.put ( "ipPlanId", zyIp.getPlanId () );
                    paraMap.put ( "cancelReason", remark );
                    SendMailUtil.sendFtlMail ( eMail, "mail_barcoCancleIp.ftl", paraMap, systemService );
                    if (zyIp.getContacter ().getTsBaseUser () != null && StringUtil.isNotEmpty ( zyIp.getContacter ().getTsBaseUser ().getId () )) {
                        //创建APP消息
                        CbsAppMessageEntity appMessage = new CbsAppMessageEntity ();
                        String content = "中影巴可巡检计划[" + zyIp.getPlanId () + "]已经取消，原因为：" + remark + "。";
                        appMessage.setContent ( content );
                        appMessage.setSender ( user.getId () );
                        appMessage.setReciver ( zyIp.getContacter ().getTsBaseUser ().getId () );
                        appMessage.setState ( StaticValue.DIC_APP_MESSAGE_STATE_UNREAD );
                        systemService.save ( appMessage );
                        systemService.addLog ( "新增APP消息,接受方:" + zyIp.getContacter ().getTsBaseUser ().getId () + ",内容:" + content, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL );
                    }
                } catch (Exception e) {
                }
            }
        }
        if (zyIp.getCompanyHadAreaEg ().equals ( "1" ) && zyIp.getAreaEngineer () != null && StringUtil.isNotEmpty ( zyIp.getAreaEngineer ().getId () )) {
            if (StringUtil.isNotEmpty ( zyIp.getAreaEngineer ().getEmail () )) {
                try {
                    //发送邮件
                    ZyEmailEntity eMail = new ZyEmailEntity ();
                    eMail.setEmailSubject ( "巴可巡检任务取消通知" );
                    eMail.setEmailReceiver ( zyIp.getAreaEngineer ().getEmail () );
                    Map<String, Object> paraMap = new HashMap<String, Object> ();
                    paraMap.put ( "ipPlanId", zyIp.getPlanId () );
                    paraMap.put ( "cancelReason", remark );
                    SendMailUtil.sendFtlMail ( eMail, "mail_barcoCancleIp.ftl", paraMap, systemService );
                    //创建APP消息
                    if (zyIp.getAreaEngineer ().getTsBaseUser () != null && StringUtil.isNotEmpty ( zyIp.getAreaEngineer ().getTsBaseUser ().getId () )) {
                        CbsAppMessageEntity appMessage = new CbsAppMessageEntity ();
                        String content = "中影巴可巡检计划[" + zyIp.getPlanId () + "]已经取消，原因为：" + remark + "。";
                        appMessage.setContent ( content );
                        appMessage.setSender ( user.getId () );
                        appMessage.setReciver ( zyIp.getAreaEngineer ().getTsBaseUser ().getId () );
                        appMessage.setState ( StaticValue.DIC_APP_MESSAGE_STATE_UNREAD );
                        systemService.save ( appMessage );
                        systemService.addLog ( "新增APP消息,接受方:" + zyIp.getAreaEngineer ().getTsBaseUser ().getId () + ",内容:" + content, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL );
                    }
                } catch (Exception e) {
                }
            }
        }
        if (zyIp.getEngineer () != null && StringUtil.isNotEmpty ( zyIp.getEngineer ().getId () )) {
            if (StringUtil.isNotEmpty ( zyIp.getEngineer ().getEmail () )) {
                try {
                    //发送邮件
                    ZyEmailEntity eMail = new ZyEmailEntity ();
                    eMail.setEmailSubject ( "巴可巡检任务取消通知" );
                    eMail.setEmailReceiver ( zyIp.getEngineer ().getEmail () );
                    Map<String, Object> paraMap = new HashMap<String, Object> ();
                    paraMap.put ( "ipPlanId", zyIp.getPlanId () );
                    paraMap.put ( "cancelReason", remark );
                    SendMailUtil.sendFtlMail ( eMail, "mail_barcoCancleIp.ftl", paraMap, systemService );
                    //创建APP消息
                    if (zyIp.getEngineer ().getTsBaseUser () != null && StringUtil.isNotEmpty ( zyIp.getEngineer ().getTsBaseUser ().getId () )) {
                        CbsAppMessageEntity appMessage = new CbsAppMessageEntity ();
                        String content = "中影巴可巡检计划[" + zyIp.getPlanId () + "]已经取消，原因为：" + remark + "。";
                        appMessage.setContent ( content );
                        appMessage.setSender ( user.getId () );
                        appMessage.setReciver ( zyIp.getEngineer ().getTsBaseUser ().getId () );
                        appMessage.setState ( StaticValue.DIC_APP_MESSAGE_STATE_UNREAD );
                        systemService.save ( appMessage );
                        systemService.addLog ( "新增APP消息,接受方:" + zyIp.getEngineer ().getTsBaseUser ().getId () + ",内容:" + content, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL );
                    }
                } catch (Exception e) {
                }
            }
        }

        /*StringBuffer sql = new StringBuffer();
        sql.append(" SELECT ");
        sql.append(" 	ct.email,ct.base_id AS tsUserId ");
        sql.append(" FROM ");
        sql.append(" 	zy_contacts ct ");
        sql.append(" LEFT JOIN t_s_base_user bu on ct.base_id = bu.ID ");
        sql.append(" LEFT JOIN act_hi_actinst aha on bu.username = aha.ASSIGNEE_ ");
        sql.append(" WHERE ");
        sql.append(" 	aha.PROC_INST_ID_ = '").append(zyIP.getProcesssId()).append("' ");
        sql.append(" ORDER BY aha.START_TIME_ DESC; ");
        List<Map<String, Object>> mapList = super.findForJdbc(sql.toString());
        String emailAddress = "",ctUserId = "";
        if (mapList.size() > 0) {
            emailAddress = mapList.get(0).get("email") != null ? mapList.get(0).get("email").toString() : "";
            ctUserId = mapList.get(0).get("tsUserId") != null ? mapList.get(0).get("tsUserId").toString() : "";
        }
        try {
        	TSUser user = ResourceUtil.getSessionUserName();
        	if(emailAddress != null){
        		//发送邮件
        		ZyEmailEntity eMail = new ZyEmailEntity();
        		eMail.setEmailSubject("巴可巡检任务取消通知");
        		eMail.setEmailReceiver(emailAddress);
        		Map<String, Object> paraMap = new HashMap<String, Object>();
        		paraMap.put("ipPlanId", zyIP.getPlanId());
        		paraMap.put("cancelReason", remark);
        		SendMailUtil.sendFtlMail(eMail, "mail_barcoCancleIp.ftl", paraMap, systemService);
        	}
            if(ctUserId != null){
            	//创建APP消息
            	CbsAppMessageEntity appMessage = new CbsAppMessageEntity();
            	String content = "中影巴可巡检计划["+zyIP.getPlanId()+"]已经取消，原因为："+remark+"。";
            	appMessage.setContent(content);
            	appMessage.setSender(user.getId());
            	appMessage.setReciver(ctUserId);
            	appMessage.setState(StaticValue.DIC_APP_MESSAGE_STATE_UNREAD);
            	systemService.save(appMessage);
            	systemService.addLog("新增APP消息,接受方:" + ctUserId + ",内容:" + content, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);
            }
        } catch (Exception e) {
        }*/
    }

    @Override
    public void doEngineerUpdateIp(String id, String engineerOrderTime, String engineerRemark) {
        ZyInspectionPlanEntity zyIP = super.get ( ZyInspectionPlanEntity.class, id );
        if (StringUtil.isNotEmpty ( engineerOrderTime )) {
            String opration = "填写";
            if (null != zyIP.getEngineerOrderTime ()) {
                opration = "修改";
            }
            Date orderTime = DateUtils.str2Date ( engineerOrderTime, DateUtils.date_sdf );
            zyIP.setEngineerOrderTime ( orderTime );
            //默认巡检开始时间就记一次 ，且是在工程师第一次填写上门时间的时候
            if (zyIP.getEngineerOrderTimeCount () < 2) {//amy 20160801 修改需求，巡检开始时间 默认设置为预约上门时间，只记两次
                zyIP.setBeginTime ( orderTime );
            }
            if (null != orderTime) {
                zyIP.setEndTime ( orderTime );// amy 20160801 修改需求，巡检结束时间 默认设置为预约上门时间，每次都记（一共就能修改一次）
            }
            //保存巡检计划流程记录
            ZyPlanRecordEntity zyPlanRecord = new ZyPlanRecordEntity ();
            zyPlanRecord.setBusId ( zyIP.getId () );
            zyPlanRecord.setPlanState ( zyIP.getState () );
            zyPlanRecord.setProcInsId ( zyIP.getProcesssId () );
            zyPlanRecord.setRemark ( "工程师" + opration + "预约上门时间" );
            Calendar cl = Calendar.getInstance ();
            cl.setTime ( new Date () );
            cl.add ( Calendar.MILLISECOND, 1 );//APP操作的时候，签到和填写预约上门时间是在一起的。导致app显示巡检记录按时间排序先后出问题。所以这里加1秒钟
            zyPlanRecord.setCreateDate ( cl.getTime () );//webService调用时 没有session 取不到值
            zyPlanRecord.setCreateBy ( null != zyIP.getEngineer () ? zyIP.getEngineer ().getTsBaseUser ().getUserName () : null );//webService调用时 没有session 取不到值
            zyPlanRecord.setCreateName ( null != zyIP.getEngineer () ? zyIP.getEngineer ().getTsBaseUser ().getRealName () : null );//webService调用时 没有session 取不到值
            systemService.save ( zyPlanRecord );
            /*//发送短信 应amy要求 不给影院发短信 2016-12-12
            Map<String, Object> paraMap = new HashMap<String, Object>();
            paraMap.put("cinemaName", zyIP.getEquipmentSpare().getZyCinema().getName());
            paraMap.put("esType", zyIP.getEquipmentSpare().getType().getTypeDesc());
            paraMap.put("esSn", zyIP.getEquipmentSpare().getSn());
            paraMap.put("orderTime", DateUtils.date2Str(orderTime, DateUtils.date_sdf_wz));
            paraMap.put("engineerName", zyIP.getEngineer().getName());
            ZyContactsEntity cinemaIpContact = this.queryCinemaInspectionContact(zyIP.getEquipmentSpare().getZyCinema().getId());
            if (null != cinemaIpContact) {
                paraMap.put("cellphone", zyIP.getEngineer().getCellphone());
                if (StringUtil.isNotEmpty(cinemaIpContact.getCellphone1())) {
                    SendMessage.sendSMSFTL(cinemaIpContact.getCellphone1(), "message_sysSendToCmContact.ftl", paraMap, systemService);
                } else if (StringUtil.isNotEmpty(cinemaIpContact.getCellphone2())) {
                    SendMessage.sendSMSFTL(cinemaIpContact.getCellphone2(), "message_sysSendToCmContact.ftl", paraMap, systemService);
                }
            }*/
        }
        if (!engineerRemark.equals ( "" )) {
            zyIP.setEngineerRemark ( engineerRemark );
        }
        zyIP.setEngineerOrderTimeCount ( zyIP.getEngineerOrderTimeCount () + 1 );
        super.saveOrUpdate ( zyIP );
    }

    @Override
    public List<String> getPlanIdsByReportExceptionConditions(String year, String month, String exType, String ttId) {
        StringBuffer sql = new StringBuffer ();
        sql.append ( " SELECT " );
        sql.append ( "   ir.inspection_plan_id AS planId " );
        sql.append ( " FROM " );
        sql.append ( "   zy_inspection_report ir " );
        sql.append ( " LEFT JOIN zy_report_exceptions re on re.report_id = ir.id " );
        sql.append ( " LEFT JOIN zy_inspection_plan ip ON ip.id = ir.inspection_plan_id " );
        sql.append ( " LEFT JOIN zy_equipment_spare es ON es.id = ip.equipment_spare_id " );
        sql.append ( " LEFT JOIN t_s_territory tt ON tt.id = es.city_id " );
        sql.append ( " LEFT JOIN t_s_territory ptt ON ptt.id = tt.territoryparentid " );
        sql.append ( " WHERE " );
        sql.append ( "   re.`year` = '" ).append ( year ).append ( "' " );
        if (StringUtil.isNotEmpty ( month )) {
            sql.append ( " AND re.`month` = '" ).append ( month ).append ( "' " );
        }
        if (StringUtil.isNotEmpty ( exType )) {//如果exType有值，则是在 机型汇总里点击进来的
            switch (exType) {
                case "1"://零地电压异常
                    sql.append ( " AND re.is_zero_ground_voltage_ex = 1 " );
                    break;
                case "2"://湿度过大
                    sql.append ( " AND re.is_humidity_ex = 1 " );
                    break;
                case "3"://温度异常
                    sql.append ( " AND re.is_temperature_ex = 1 " );
                    break;
                case "4"://冷却液压力异常
                    sql.append ( " AND re.is_coolant_pressure_ex = 1 " );
                    break;
                case "5"://冷却液面高度异常
                    sql.append ( " AND re.is_coolant_height_ex = 1 " );
                    break;
                case "6"://亮度低
                    sql.append ( " AND re.is_brightness_ex = 1 " );
                    break;
                case "7"://风速异常
                    sql.append ( " AND re.is_wind_speed_ex = 1 " );
                    break;
                case "8"://参加培训人数不足
                    sql.append ( " AND re.is_training_num_ex = 1 " );
                    break;
            }
        } else if (StringUtil.isNotEmpty ( ttId )) {//如果省份Id有值，则是在 区域汇总里点进来的
            sql.append ( " AND ptt.id = '" ).append ( ttId ).append ( "' " );
        }
        List<Map<String, Object>> rs = systemService.findForJdbc ( sql.toString () );
        List<String> planIds = new ArrayList<String> ();
        for (Map<String, Object> map : rs) {
            planIds.add ( map.get ( "planId" ).toString () );
        }
        return planIds;
    }

    @Override
    public boolean judgeEngineerLastPersonIsAreaEngineer(String processsId, Integer index) {
        List<HistoricTaskInstance> hisTasks = historyService.createHistoricTaskInstanceQuery ().finished ().processInstanceId ( processsId ).orderByHistoricTaskInstanceStartTime ().desc ().list ();
        if (null == hisTasks.get ( index )) {
            return false;
        }
        String lastAssignee = hisTasks.get ( index ).getAssignee ();
        List<Map<String, Object>> res = systemService.findForJdbc ( "SELECT GROUP_ID_ FROM act_id_membership WHERE USER_ID_ = ?", lastAssignee );
        if (res != null && res.size () > 0) {
            if (res.get ( 0 ).get ( "GROUP_ID_" ).toString ().equals ( StaticValue.RULE_CODE_AREA_ENGINEER )) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean judgeForBatchOperateMission(ZyInspectionPlanEntity zyIP, AjaxJson j, String userId) {
        //按钮 保存 巡检任务的 过滤条件
        List<String> btnSavePlanRules = new ArrayList<String> ();
        btnSavePlanRules.add ( StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY );
        if (zyIP.getCompanyHadAreaEg ().equals ( "1" )) {
            btnSavePlanRules.add ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_REFUSED );
        } else {
            btnSavePlanRules.add ( StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED );
        }
        String message = "";
        boolean flag = true;//默认可以操作
        if (null != zyIP.getContacter () && null != zyIP.getContacter ().getTsBaseUser () && StringUtil.isNotEmpty ( zyIP.getContacter ().getTsBaseUser ().getId () )) {//如果其中有一项为空 则不能保存
            if (!zyIP.getContacter ().getTsBaseUser ().getId ().equals ( userId )) {//如果当前登录人和 巡检计划第三方联系人不同，则不能保存
                message = "当前巡检任务已指派其它负责人";
                flag = false;
            } else {
                if (!btnSavePlanRules.contains ( zyIP.getState () )) {//如果当前巡检计划状态 不符合规则，则不能保存
                    message = "所选任务中包括不能操作的任务，请重新选择";
                    flag = false;
                } else {
                    //首次派单成功,第一次派单机会已经使用
                    zyIP.setIsTrun ( "1" );
                    systemService.saveOrUpdate ( zyIP );
                }
            }
        } else {
            message = "当前任务没有第三方联系人";
            flag = false;
        }
        if (null != j) {
            j.setSuccess ( flag );
            j.setMsg ( message );
        }
        return flag;
    }

    @Override
    public boolean judgeForBatchOperateMissionPlan(ZyInspectionPlanEntity zyIP, AjaxJson j, String userId) {
        //按钮 保存 巡检任务的 过滤条件
        List<String> btnSavePlanRules = new ArrayList<String> ();
        btnSavePlanRules.add ( StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY );
        if (zyIP.getCompanyHadAreaEg ().equals ( "1" )) {
            btnSavePlanRules.add ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_REFUSED );
            //1、巡检计划在“区域工程师接受”时仍可以拒绝。
            btnSavePlanRules.add ( StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED );
        } else {
            btnSavePlanRules.add ( StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED );
            //1、巡检计划在“工程师接受”时仍可以拒绝。
            btnSavePlanRules.add ( StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED );
        }
        String message = "";
        boolean flag = true;//默认可以操作
        if (null != zyIP.getContacter () && null != zyIP.getContacter ().getTsBaseUser () && StringUtil.isNotEmpty ( zyIP.getContacter ().getTsBaseUser ().getId () )) {//如果其中有一项为空 则不能保存
            if (!zyIP.getContacter ().getTsBaseUser ().getId ().equals ( userId )) {//如果当前登录人和 巡检计划第三方联系人不同，则不能保存
                message = "当前巡检任务已指派其它负责人";
                flag = false;
            } else {
                if (!btnSavePlanRules.contains ( zyIP.getState () )) {//如果当前巡检计划状态 不符合规则，则不能保存
                    message = "所选任务中包括不能操作的任务，请重新选择";
                    flag = false;
                } else {
                    //首次派单成功,第一次派单机会已经使用
                    zyIP.setIsTrun ( "1" );
                    systemService.saveOrUpdate ( zyIP );
                }
            }
        } else {
            message = "当前任务没有第三方联系人";
            flag = false;
        }
        if (null != j) {
            j.setSuccess ( flag );
            j.setMsg ( message );
        }
        return flag;
    }

    @Override
    public boolean judgeForBatchOperateMissions(ZyInspectionPlanEntity zyIP, AjaxJson j, String userId) {

        //按钮 保存 巡检任务的 过滤条件
        List<String> btnSavePlanRules = new ArrayList<String> ();
        btnSavePlanRules.add ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED );
        if (zyIP.getCompanyHadAreaEg ().equals ( "1" )) {
            btnSavePlanRules.add ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_ASSIGNED );
            btnSavePlanRules.add ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_REFUSED );
            btnSavePlanRules.add ( StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED );
            btnSavePlanRules.add ( StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED );
        } else {
            btnSavePlanRules.add ( StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED );
            btnSavePlanRules.add ( StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED );
        }
        String message = "";
        boolean flag = true;//默认可以操作
        if (null != zyIP.getContacter () && null != zyIP.getContacter ().getTsBaseUser () && StringUtil.isNotEmpty ( zyIP.getContacter ().getTsBaseUser ().getId () )) {//如果其中有一项为空 则不能保存
            if (!zyIP.getContacter ().getTsBaseUser ().getId ().equals ( userId )) {//如果当前登录人和 巡检计划第三方联系人不同，则不能保存
                message = "当前巡检任务已指派其它负责人";
                flag = false;
            } else {
                if (!btnSavePlanRules.contains ( zyIP.getState () )) {//如果当前巡检计划状态 不符合规则，则不能保存
                    message = "所选任务中包括不能操作的任务，请重新选择";
                    flag = false;
                }
            }
        } else {
            message = "当前任务没有第三方联系人";
            flag = false;
        }
        if (null != j) {
            j.setSuccess ( flag );
            j.setMsg ( message );
        }
        return flag;
    }

    @Override
    public String judgeViewOrUpdateReport(String zyIpid) {
        String viewOrUpdateReportFlag = "0";
        ZyInspectionReportEntity zyIpReport = systemService.findUniqueByProperty ( ZyInspectionReportEntity.class, "inspectionPlanId", zyIpid );
        if (zyIpReport != null) {
            viewOrUpdateReportFlag = "1";
        }
        return viewOrUpdateReportFlag;
    }

    @Override
    public List<Map<String, Object>> queryIpForEsDetailsPage(String esSn) {
        StringBuilder sql = new StringBuilder ();

        sql.append ( " SELECT " );
        sql.append ( "	IFNULL(ipRecord.plan_id, '') plan_id, IFNULL(ipRecord.actual_date, '') actual_date, " );
        sql.append ( " 	IFNULL(ipRecord.company, '') company, IFNULL(ipRecord.engineer, '') engineer, " );
        sql.append ( " 	IFNULL(ipRecord.house, '') house, IFNULL(ipRecord.yt_rm_temperature,'') yt_rm_temperature, " );
        sql.append ( " 	IFNULL(ipRecord.yt_rm_humidity,'') yt_rm_humidity, IFNULL(ipRecord.lq_coolant_liquid_h,'') lq_coolant_liquid_h, " );
        sql.append ( " 	IFNULL(ipRecord.lq_score_coolant,'') lq_score_coolant, IFNULL(ipRecord.lq_vent_speed,'') lq_vent_speed, " );
        sql.append ( " 	IFNULL(ipRecord.qj_dust_filter_cl_mp,'') qj_dust_filter_cl_mp, IFNULL(ipRecord.xl_zero_voltage,'') xl_zero_voltage, " );
        sql.append ( " 	IFNULL(ipRecord.xd_run_time, '') xd_run_time, IFNULL(ipRecord.xd_run_count, '') xd_run_count, " );
        sql.append ( " 	IFNULL(ipRecord.gx_light_path,'') gx_light_path, IFNULL(ipRecord.yx_light_c, '') yx_light_c, " );
        sql.append ( " 	IFNULL(ipRecord.total_run_time,'') total_run_time, IFNULL(ipRecord.after_score, '') after_score, " );
        sql.append ( " 	IFNULL(ipRecord.eng_item_id, '') eng_item_sn, IFNULL(ipRecord.ti_icp_item_id,'') ti_icp_item_sn, " );
        sql.append ( " 	IFNULL(ipRecord.lps_item_id, '') lps_item_sn, IFNULL(ipRecord.enigma_item_id,'') enigma_item_sn, " );
        sql.append ( " 	IFNULL(ipRecord.controler_item_id,'') controler_item_sn, IFNULL(ipRecord.smps_item_id, '') smps_item_sn, " );
        sql.append ( " 	IFNULL(ipRecord.server_brand, '') server_brand, IFNULL(ipRecord.server_model, '') server_model, " );
        sql.append ( " 	IFNULL(ipRecord.comprehensive_evaluation,'') comprehensive_evaluation " );
        sql.append ( " FROM " );
        sql.append ( " 	zy_inspection_record ipRecord " );
        sql.append ( " WHERE " );
        sql.append ( " 	ipRecord.spare_sn = '" ).append ( esSn ).append ( "' " );

        return findForJdbc ( sql.toString () );
    }

    @Override
    public void exportInspectionPlan(HttpServletRequest request, HttpServletResponse response) {
        OutputStream out = null;
        try {
            String fileName = "巡检计划.xlsx";
            response.setCharacterEncoding ( "text/html;charset=utf-8" );
            response.setContentType ( "application/x-msdownload;" );
            response.setHeader ( "Content-disposition", "attachment; filename=" + (new String ( fileName.getBytes ( "gb2312" ), "ISO8859-1" )) );
            out = response.getOutputStream ();
            String[] planIdsArr = oConvertUtils.getString ( request.getParameter ( "planIds" ) ).split ( "," );
            StringBuffer sql = new StringBuffer ();
            sql.append ( " SELECT * FROM ( " );
            sql.append ( " SELECT " );
            sql.append ( "	ip.id AS ipId, et.type_desc, es.sn, tp1.typename, dp.bp_code, ty_p.territoryname AS province, ty.territoryname AS city, " );
            sql.append ( "	cm.`name` AS cmName, cm.address AS cmAddress, " );
            sql.append ( "	ct.`name` AS ctName, ct.cellphone1 AS ctCellphone, ct.fax AS ctFax, " );
            sql.append ( "	ct2.`name` AS ct2Name, ct2.cellphone1 AS ct2Cellphone, " );
            sql.append ( "	dp2.departname AS ipCompanyName, MONTH(ip.ip_plan_date) AS ipPlanDate, " );
            sql.append ( "	ct3.`name` AS ct3Name, ct3.cellphone1 AS ct3Cellphone, " );
            sql.append ( "	es.install_date, es.last_year_inspection_date, ip.end_time AS esInpsectionEndTime, " );
            sql.append ( "	ip.begin_time, ip.end_time, eg.`name` AS egName, " );
            sql.append ( "	rm.room_num, rm.screen_type, rm.screen_plus, rm.screen_width, rm.screen_hight, rm.curtain_width, rm.curtain_hight,rm.show_km, " );
            sql.append ( "	ir.gx_cam_lens, et_1.type_desc AS serverBrandVal, ir.server_model, p_et_1.type_desc AS '服务器品牌', ir.yt_rm_temperature, ir.yt_rm_humidity,  " );
            sql.append ( "	ir.gx_score_cam_lens,ir.gx_score_reflective_lens, " );
            sql.append ( "	ir.lq_coolant_h, ir.lq_coolant_liquid_h, ir.xd_power, ir.xd_brand, ir.xd_run_time, ir.xd_run_count, " );
//          单相电压/三相电压修改  modify start Amy 
            //            sql.append("	ir.xd_score_joints, ir.total_run_time, ir.xl_voltage_type, ir.xl_voltage, ir.xl_zero_voltage,  ");
            sql.append ( "	ir.xd_score_joints, ir.total_run_time,  ");
            sql.append ( "	case ir.xl_voltage_type WHEN '2' then '' else ir.xl_voltage end as 'xl_voltage_type', case ir.xl_voltage_type WHEN '2' then ir.xl_voltage else  '' end as 'xl_voltage' , ir.xl_zero_voltage,    ");
//          单相电压/三相电压修改  modify end Amy
//          影响亮度因素修改  modify start Amy 
//            sql.append("	ir.yx_score_focus, tp.typename AS gxLightPathVal, ir.yx_light_c, ir.yx_light_center, ir.yx_influ_light_factor,  ");
            sql.append ( "	ir.yx_score_focus, tp.typename AS gxLightPathVal, ir.yx_light_c, ir.yx_light_center, tp2.typename as 'yx_influ_light_factor',  ");
//          影响亮度因素修改  modify end Amy 
            sql.append ( "	ir.yx_score_3d, ir.rj_barcor_dp_udt, ir.rj_dctp_udt, ir.rj_ti_udt, ir.rj_icmp_udt, ir.rj_ims1000_udt, IF(ir.og_mp = 'on','是','否') AS og_mp, ir.score_projector_mb,  " );
            sql.append ( "	ir.before_score, ir.after_score, ir.comprehensive_evaluation, ir.yt_problem,' ' AS '影院反馈(期望和评价)', " );
            sql.append ( "	ir.training_num, ir.training_score, ir.training_point,IF(ir.had_change_notice = 'on','是','否') AS had_change_notice,  " );
            sql.append ( "	ei.item AS engItemIdVal, ir.eng_item_sn, ir.eng_security_sn, ir.eng_exception_sign, " );
            sql.append ( "	ei_2.item AS tiIcpItemIdVal, ir.ti_icp_item_sn, ir.ti_icp_security_sn, ir.ti_icp_exception_sign, " );
            sql.append ( "	ei_3.item AS lpsItemIdVal, ir.lps_item_sn, ir.lps_security_sn, ir.lps2_item_sn, ir.lps2_security_sn, ir.lps3_item_sn, ir.lps3_security_sn, '' AS '备件信息异常确认签字-LPS(Y/N)', " );
            sql.append ( "	ei_4.item AS enigmaItemIdVal, ir.enigma_item_sn, ir.enigma_security_sn, ir.enigma_exception_sign, " );
            sql.append ( "	ei_5.item AS controlerItemIdVal, ir.controler_item_sn, ir.controler_security_sn, ir.controler_exception_sign, " );
            sql.append ( "	ei_6.item AS smpsItemIdVal, ir.smps_item_sn, ir.smps_security_sn, ir.smps_excption_sign, " );
            sql.append ( "	ir.lq_vent_speed, " );
            sql.append ( "	IF ( ir.original_cooling = 'on', '是', '否' ) AS original_cooling, ir.clo_luminance, tp3.typename as yt_problem1, " );
            /******************************正常使用功率、亮度最大值、ldm新增 add by sll begin******************************/
            sql.append ("   CONCAT(ir.normal_power,'%') AS normalPower, ");
            sql.append ("   ir.yx_light_max AS yxLightMax, ");
            sql.append ("   ei_7.item AS ldmItemIdVal, ");
            sql.append ("   ir.ldm1_sn AS ldm1Sn, ");
            sql.append ("   ir.ldm1_security_sn AS ldm1SecuritySn, ");
            sql.append ("   ir.ldm2_sn AS ldm2Sn, ");
            sql.append ("   ir.ldm2_security_sn AS ldm2SecuritySn, ");
            sql.append ("   ir.ldm_exception_sign AS ldmExceptionSign ");
            /******************************正常使用功率、亮度最大值、ldm新增 add by sll end******************************/
            sql.append ( " FROM " );
            sql.append ( " 	zy_inspection_plan ip " );
            sql.append ( " LEFT JOIN zy_equipment_spare es ON es.id = ip.equipment_spare_id " );
            sql.append ( " LEFT JOIN zy_equipment_type et ON et.id = es.type " );
            sql.append ( " LEFT JOIN zy_cinema cm ON cm.id = es.belong_cinema_id " );
            sql.append ( " LEFT JOIN t_s_depart dp ON dp.id = es.belong_org_id " );
            sql.append ( " LEFT JOIN t_s_depart dp2 ON dp2.org_code = ip.company " );
            sql.append ( " LEFT JOIN t_s_territory ty ON ty.id = cm.province " );
            sql.append ( " LEFT JOIN t_s_territory ty_p ON ty_p.ID = ty.territoryparentid " );
            sql.append ( " LEFT JOIN zy_contacts ct ON ct.belong_cinema = cm.id AND ct.position = '" ).append ( StaticValue.DIC_CONTACT_POSITION_C_MANAGER ).append ( "' " );
            sql.append ( " LEFT JOIN zy_contacts ct2 ON ct2.belong_cinema = cm.id AND ct2.position = '" ).append ( StaticValue.DIC_CONTACT_POSITION_C_TECHNICAL_DIRECTOR ).append ( "' " );
            sql.append ( " LEFT JOIN zy_contacts ct3 ON ct3.id = ip.charge_person " );
            sql.append ( " LEFT JOIN zy_engineer eg ON eg.id = ip.engineer " );
            sql.append ( " LEFT JOIN zy_room rm ON rm.id = es.house " );
            sql.append ( " LEFT JOIN zy_inspection_report ir ON ir.inspection_plan_id = ip.id " );
            sql.append ( " LEFT JOIN zy_equipment_type et_1 on et_1.id = ir.server_brand " );
            sql.append ( " LEFT JOIN zy_equipment_type p_et_1 on p_et_1.id = et_1.parent_id " );
            sql.append ( " LEFT JOIN t_s_typegroup tg on tg.typegroupcode = '" ).append ( StaticValue.DIC_LIGHT_PATH ).append ( "' " );
            sql.append ( " LEFT JOIN t_s_type tp on tp.typecode = ir.gx_light_path AND tg.id = tp.typegroupid " );
            sql.append ( " LEFT JOIN t_s_typegroup tg1 on tg1.typegroupcode = '" ).append ( StaticValue.DIC_PLAN_STATE ).append ( "' " );
            sql.append ( " LEFT JOIN t_s_type tp1 on tp1.typecode = ip.state AND tg1.id = tp1.typegroupid " );
//          影响亮度因素修改  modify start Amy 
            sql.append ( " LEFT JOIN t_s_typegroup tg2 on tg2.typegroupcode = '").append(StaticValue.DIC_YXINFLULIGHTFACOTR).append("' ");
            sql.append ( " LEFT JOIN t_s_type tp2 on tp2.typecode = ir.yx_influ_light_factor AND tg2.id = tp2.typegroupid  ");
//          影响亮度因素修改  modify end Amy
            /*主要异常项*/
            sql.append ( "LEFT JOIN t_s_typegroup tg3 ON tg3.typegroupcode = 'ytproblem'\n" );
            sql.append ( "LEFT JOIN t_s_type tp3 ON tp3.typecode = ir.yt_problem\n" );
            sql.append ( "AND tg3.id = tp3.typegroupid");
            /*主要异常项*/
            sql.append ( " LEFT JOIN zy_es_item ei ON ei.id = ir.eng_item_id " );
            sql.append ( " LEFT JOIN zy_es_item ei_2 ON ei_2.id = ir.ti_icp_item_id " );
            sql.append ( " LEFT JOIN zy_es_item ei_3 ON ei_3.id = ir.lps_item_id " );
            sql.append ( " LEFT JOIN zy_es_item ei_4 ON ei_4.id = ir.enigma_item_id " );
            sql.append ( " LEFT JOIN zy_es_item ei_5 ON ei_5.id = ir.controler_item_id " );
            sql.append ( " LEFT JOIN zy_es_item ei_6 ON ei_6.id = ir.smps_item_id " );
            sql.append ( " LEFT JOIN zy_es_item ei_7 ON ei_7.id = ir.ldm_item_id " );
            sql.append ( " WHERE " );
            sql.append ( " 	ip.id IN ( " );
            for (int i = 0; i < planIdsArr.length; i++) {
                if (i == planIdsArr.length - 1) {
                    sql.append ( "'" + planIdsArr[i] + "'" );
                } else {
                    sql.append ( "'" + planIdsArr[i] + "'," );
                }
            }
            sql.append ( " 	) " );
            sql.append ( ") tt GROUP BY tt.ipId " );
            List<Map<String, Object>> reusltMaps = super.findForJdbc ( sql.toString () );
            TSUser user = ResourceUtil.getSessionUserName();
            systemService.addLog(user.getRealName()+"导出"+reusltMaps.size()+"条巡检计划记录", Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);
            InputStream is = ZyInspectionPlanServiceImpl.class.getClassLoader ().getResourceAsStream ( "jeecg/template/inspectionPlanTemplate.xlsx" );
            XSSFWorkbook xssf = new XSSFWorkbook ( is );
            XSSFSheet sheet = xssf.getSheetAt ( 0 );
            int rowNum = 1;
            for (Map<String, Object> dataMap : reusltMaps) {
                XSSFRow row = sheet.createRow ( rowNum );
                int cellNum = 0, index = 0;
                for (String key : dataMap.keySet ()) {
                    if (index == 0) {
                        index++;
                        continue;
                    }
                    XSSFCell cell = row.createCell ( cellNum );
                    cell.setCellValue ( dataMap.get ( key ) != null ? dataMap.get ( key ).toString () : "" );
                    cellNum++;
                }
                rowNum++;
            }
            xssf.write ( out );
        } catch (IOException e) {
            e.printStackTrace ();
        } finally {
            try {
                if (out != null) {
                    out.flush ();
                    out.close ();
                }
            } catch (IOException e) {
                e.printStackTrace ();
            }
        }
    }

    @Override
    public Map<String, ZyContactsEntity> queryCinemaIpContactsMap() {
        Map<String, ZyContactsEntity> map = new HashMap<String, ZyContactsEntity> ();
        StringBuffer hql = new StringBuffer ();
        hql.append ( " FROM " );
        hql.append ( " ZyContactsEntity ct " );
        hql.append ( " WHERE " );
        hql.append ( " ct.state = '" ).append ( StaticValue.DIC_ENGINEER_STATE_ONJOB ).append ( "' " );
        hql.append ( " AND ct.isDelete = '0' " );
        hql.append ( " AND ct.type = '" ).append ( StaticValue.DIC_CONTACT_TYPE_CINEMA_CONTACT ).append ( "' " );
        hql.append ( " AND ct.conBusiness like '%" ).append ( StaticValue.DIC_BUS_SCOPE_INSPECTION ).append ( "%' " );
        List<ZyContactsEntity> zyCts = super.findHql ( hql.toString () );
        if (null != zyCts && zyCts.size () > 0) {
            for (ZyContactsEntity ct : zyCts) {
                if (null == ct.getBelongCinema ()) {
                    continue;
                }
                map.put ( ct.getBelongCinema ().getId (), ct );
            }
        }
        return map;
    }

    @Override
    public ZyContactsEntity queryCinemaInspectionContact(String cinemaId) {
        Map<String, ZyContactsEntity> ctsMap = queryCinemaIpContactsMap ();
        if (null != ctsMap) {
            return ctsMap.get ( cinemaId );
        }
        return null;
//    	ZyContactsEntity zyCt = new ZyContactsEntity();
//        StringBuffer hql = new StringBuffer();
//        hql.append(" FROM ");
//        hql.append(" ZyContactsEntity ct ");
//        hql.append(" WHERE ");
//        hql.append(" ct.belongCinema.id = '").append(cinemaId).append("'");
//        hql.append(" AND ct.state = '").append(StaticValue.DIC_ENGINEER_STATE_ONJOB).append("' ");
//        hql.append(" AND ct.isDelete = '0' ");
//        hql.append(" AND ct.type = '").append(StaticValue.DIC_CONTACT_TYPE_CINEMA_CONTACT).append("' ");
//        hql.append(" AND ct.conBusiness like '%").append(StaticValue.DIC_BUS_SCOPE_INSPECTION).append("%' ");
//        List<ZyContactsEntity> zyCts = super.findHql(hql.toString());
//        if (null != zyCts && zyCts.size() > 0) {
//            zyCt = zyCts.get(0);//以为这里之前 影院的巡检联系人没有加 唯一校验,所以可能数据库中存在 一个影院多个巡检联系人,避免出错,这个采用 get 0
//        }
//        return zyCt;
    }

    @Override
    public boolean judgeIpOfEgRefusePlan(String id, String type, AjaxJson j, String userId) {
        String opration = "操作";
        if (StringUtil.isNotEmpty ( type ) && type.equals ( "refuse" )) {
            opration = "拒绝";
        } else if (StringUtil.isNotEmpty ( type ) && type.equals ( "assign" )) {
            opration = "接受";
        }
        ZyInspectionPlanEntity zyIP = systemService.get ( ZyInspectionPlanEntity.class, id );
        String message = "";
        boolean flag = true;
        if (zyIP.getEngineer ().getTsBaseUser ().getId ().equals ( userId )) {
            //工程师不能接受或拒绝的计划包括  已经接受的 ，已拒绝的，工程师实施中，工程师已提交巡检报告，已完成巡检计划,巡检计划已取消
            if(StringUtil.isNotEmpty ( type ) && type.equals ( "assign" )){
                if (zyIP.getState ().equals ( StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED )
                        || zyIP.getState ().equals ( StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED )
                        || zyIP.getState ().equals ( StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT )
                        || zyIP.getState ().equals ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE )
                        || zyIP.getState ().equals ( StaticValue.DIC_PLAN_STATE_INSPECTION_CANCEL )
                        ) {
                    flag = false;
                    message = "所选任务中包括不能" + opration + "的任务，请重新选择";
                }
            }
            if(StringUtil.isNotEmpty ( type ) && type.equals ( "refuse" )){
                if (zyIP.getState ().equals ( StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED )
//                        || zyIP.getState ().equals ( StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED )
                        || zyIP.getState ().equals ( StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT )
                        || zyIP.getState ().equals ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE )
                        || zyIP.getState ().equals ( StaticValue.DIC_PLAN_STATE_INSPECTION_CANCEL )
                        ) {
                    flag = false;
                    message = "所选任务中包括不能" + opration + "的任务，请重新选择";
                }
            }

        } else {
            flag = false;
            message = "当前巡检任务已指派其它工程师";
        }
        if (null != j) {
            j.setMsg ( message );
            j.setSuccess ( flag );
        }
        return flag;
    }

    @Override
    public boolean judgePlanOfEgAddReport(String id, AjaxJson j, String userId) {
        ZyInspectionPlanEntity zyIP = systemService.get ( ZyInspectionPlanEntity.class, id );
        boolean flag = true;
        String message = "";
        if (null != zyIP.getEngineer () && null != zyIP.getEngineer ().getTsBaseUser () && StringUtil.isNotEmpty ( zyIP.getEngineer ().getTsBaseUser ().getId () )) {//如果其中有一项为空 则不能保存
            //只有在 工程师实施中的才可以填写巡检报告
            if (!zyIP.getState ().equals ( StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT )) {
                flag = false;
                message = "所选任务不能填写巡检报告，请重新选择";
            }
        } else {
            flag = false;
            message = "您不能操作当前任务";
        }
        if (null != j) {
            j.setMsg ( message );
            j.setSuccess ( flag );
        }
        return flag;
    }

    @Override
    public Map<String, Object> queryAppIpTpList(int type, String area, String planYear, String planMonth, String esSn, String cmId) {
        Map<String, Object> rsMap = new HashMap<String, Object> ();
        TSUser user = ResourceUtil.getSessionUserName ();
        //影院分组
        StringBuffer groupSqlpart1 = new StringBuffer ();
        groupSqlpart1.append ( " SELECT " );
        groupSqlpart1.append ( " 	IFNULL(cm.id,'无') AS cmId, " );
        groupSqlpart1.append ( " 	IFNULL(cm.`name`,'无') AS cmName, " );
        groupSqlpart1.append ( " 	ct.`name` AS cmCtIpName, " );
        groupSqlpart1.append ( " 	ct.cellphone1, " );
        groupSqlpart1.append ( " 	ct.cellphone2, " );
        groupSqlpart1.append ( " 	IFNULL(cm.address,'无') AS address " );
        groupSqlpart1.append ( " FROM " );
        groupSqlpart1.append ( " 	zy_inspection_plan ip " );
        groupSqlpart1.append ( " LEFT JOIN zy_equipment_spare es ON es.id = ip.equipment_spare_id " );
        groupSqlpart1.append ( " LEFT JOIN zy_cinema cm ON cm.id = es.belong_cinema_id " );
        groupSqlpart1.append ( " LEFT JOIN t_s_territory tt ON tt.id = cm.province " );
        groupSqlpart1.append ( " LEFT JOIN zy_contacts ct ON ct.belong_cinema = cm.id " );
        groupSqlpart1.append ( " 	AND ct.state = '" ).append ( StaticValue.DIC_ENGINEER_STATE_ONJOB ).append ( "' " );
        groupSqlpart1.append ( " 	AND ct.is_delete = 0 " );
        groupSqlpart1.append ( " 	AND ct.type = '" ).append ( StaticValue.DIC_CONTACT_TYPE_CINEMA_CONTACT ).append ( "' " );
        groupSqlpart1.append ( " 	AND ct.con_business LIKE '%" ).append ( StaticValue.DIC_LINK_BUSINESS_INSPECTION ).append ( "%' " );
        StringBuffer groupSqlpart2 = new StringBuffer ();
        groupSqlpart2.append ( " GROUP BY " );
        groupSqlpart2.append ( "	cm.`name` " );
        //巡检计划
        StringBuffer detailSql = new StringBuffer ();
        detailSql.append ( " SELECT " );
        detailSql.append ( " 	ip.id AS ipId, " );
        detailSql.append ( " 	ip.state, " );
        detailSql.append ( "	CASE ip.state WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY ).append ( "' THEN '1' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED ).append ( "' THEN '2' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_REFUSED ).append ( "' THEN '3' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_ASSIGNED ).append ( "' THEN '4' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_REFUSED ).append ( "' THEN '5' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED ).append ( "' THEN '6' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED ).append ( "' THEN '7' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT ).append ( "' THEN '8' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE ).append ( "' THEN '9' END AS ipState, " );
        detailSql.append ( " 	es.sn, " );
        detailSql.append ( " 	ip.plan_id AS planId, " );
        detailSql.append ( " 	MONTH(ip.ip_plan_date) AS ipMonth, " );
        detailSql.append ( " 	DATE_FORMAT(ip.create_date,'%Y-%m-%d') AS createDate, " );
        detailSql.append ( " 	IFNULL(cm.id,'无') AS cmId " );
        detailSql.append ( " FROM " );
        detailSql.append ( " 	zy_inspection_plan ip " );
//        detailSql.append(" LEFT JOIN t_s_typegroup tg ON tg.typegroupcode = '").append(StaticValue.DIC_IP_MONTH).append("' ");
//        detailSql.append(" LEFT JOIN t_s_type tp ON tp.typecode = ip.plan_quarter AND tg.ID = tp.typegroupid ");
        detailSql.append ( " LEFT JOIN zy_equipment_spare es ON es.id = ip.equipment_spare_id " );
        detailSql.append ( " LEFT JOIN zy_cinema cm ON cm.id = es.belong_cinema_id " );
        detailSql.append ( " LEFT JOIN t_s_territory tt ON tt.id = cm.province " );

        //列表页上方 - 地区分组sql
        StringBuffer citySqlpart1 = new StringBuffer ();
        citySqlpart1.append ( " SELECT " );
        citySqlpart1.append ( " 	tt.ID AS id, " );
        citySqlpart1.append ( " 	tt.territoryname, " );
        citySqlpart1.append ( " 	count(ip.id) AS total " );
        citySqlpart1.append ( " FROM " );
        citySqlpart1.append ( " 	zy_inspection_plan ip " );
        citySqlpart1.append ( " LEFT JOIN zy_equipment_spare es ON es.id = ip.equipment_spare_id " );
        citySqlpart1.append ( " LEFT JOIN zy_cinema cm ON cm.id = es.belong_cinema_id " );
        citySqlpart1.append ( " LEFT JOIN t_s_territory tt ON tt.id = cm.province " );
        StringBuffer citySqlpart2 = new StringBuffer ();
        citySqlpart2.append ( " GROUP BY " );
        citySqlpart2.append ( " 	tt.ID " );
        citySqlpart2.append ( " ORDER BY " );
        citySqlpart2.append ( " 	tt.territorysort " );

        //列表上方 - 巡检年月份分组sql
        StringBuffer planQuarterSqlpart1 = new StringBuffer ();
        planQuarterSqlpart1.append ( " SELECT " );
//        planQuarterSqlpart1.append(" 	MONTH(ip.ip_plan_date) AS planMonth, ");
        planQuarterSqlpart1.append ( " 	DATE_FORMAT(ip.ip_plan_date,'%Y年-%m月') AS planYearMonth, " );
        planQuarterSqlpart1.append ( "	YEAR(ip.ip_plan_date) AS planYear, MONTH(ip.ip_plan_date) AS planMonth, " );
        planQuarterSqlpart1.append ( " 	count(ip.id) AS total " );
        planQuarterSqlpart1.append ( " FROM " );
        planQuarterSqlpart1.append ( " 	zy_inspection_plan ip " );
        planQuarterSqlpart1.append ( " LEFT JOIN zy_equipment_spare es ON es.id = ip.equipment_spare_id " );
        planQuarterSqlpart1.append ( " LEFT JOIN zy_cinema cm ON cm.id = es.belong_cinema_id " );
        planQuarterSqlpart1.append ( " LEFT JOIN t_s_territory tt ON tt.id = cm.province " );

        StringBuffer planQuarterSqlpart2 = new StringBuffer ();
        planQuarterSqlpart2.append ( " GROUP BY " );
        planQuarterSqlpart2.append ( " 	planYearMonth " );
        planQuarterSqlpart2.append ( " ORDER BY " );
        planQuarterSqlpart2.append ( " 	planYearMonth " );
        List<Map<String, Object>> areaMapList;
        List<Map<String, Object>> planMonthMapList;
        StringBuffer conditionSql = new StringBuffer ();
        List<String> idsList = zyWorkFlowService.queryUserProcess ( user.getUserName (), StaticValue.P_PROCESS_INSPECTION, true, null );
        TSDepart rootDepart = zyCommonService.getUserRootTsDepartCode ( user.getCurrentDepart () );//最上级组织（公司）
        String company = rootDepart.getOrgCode ();
        if (type == 1) {//概览
            /**------ 概览 ------*/
            StringBuffer sql = new StringBuffer ();
            sql.append ( " SELECT " );
            sql.append ( " 	COUNT(ip.id) AS total, ip.state " );
            sql.append ( " FROM " );
            sql.append ( "	zy_inspection_plan ip " );
            conditionSql.append ( " WHERE " );
            conditionSql.append ( " ( " );
            conditionSql.append ( " 	(ip.company_had_area_eg = 1 AND ip.state IN ('" )
                    .append ( StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY ).append ( "','" )
                    .append ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED ).append ( "','" )
                    .append ( StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED ).append ( "','" )
                    .append ( StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT ).append ( "','" )
                    .append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_REFUSED ).append ( "','" )
                    .append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_ASSIGNED ).append ( "','" )
                    .append ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE ).append ( "')) " );
            conditionSql.append ( " 	OR " );
            conditionSql.append ( " 	(ip.company_had_area_eg = 0 AND ip.state IN ('" )
                    .append ( StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY ).append ( "','" )
                    .append ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED ).append ( "','" )
                    .append ( StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED ).append ( "','" )
                    .append ( StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT ).append ( "','" )
                    .append ( StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED ).append ( "','" )
                    .append ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE ).append ( "')) " );
            conditionSql.append ( " ) " );
            conditionSql.append ( " AND ip.company = '" ).append ( company ).append ( "' " );//只查询指派到自己单位的
            conditionSql.append(" and YEAR(ip.ip_plan_date)=YEAR(NOW())"); //只查询本年度的
//            if (null != idsList && idsList.size () > 0) {
//                conditionSql.append ( " AND ip.id IN (" );
//                for (int i = 0; i < idsList.size (); i++) {
//                    if (i == idsList.size () - 1) {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'" );
//                    } else {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'," );
//                    }
//                }
//                conditionSql.append ( " ) " );
//            } else {
//                conditionSql.append ( " AND 1 != 1" );
//            }
            sql.append ( conditionSql.toString () );
            sql.append ( " GROUP BY " );
            sql.append ( "	ip.state " );
            List<Map<String, Object>> rtMap = super.findForJdbc ( sql.toString () );
            int alreadSendCount = 0, alreadDoneCount = 0, countTotal = 0;
            for (Map<String, Object> map : rtMap) {
                switch (map.get ( "state" ).toString ()) {
                    case StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED:
                        alreadSendCount += Integer.valueOf ( map.get ( "total" ).toString () );
                        break;
                    case StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_ASSIGNED:
                        alreadSendCount += Integer.valueOf ( map.get ( "total" ).toString () );
                        break;
                    case StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED:
                        alreadSendCount += Integer.valueOf ( map.get ( "total" ).toString () );
                        break;
                    case StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT:
                        alreadSendCount += Integer.valueOf ( map.get ( "total" ).toString () );
                        break;
                    case StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE:
                        alreadSendCount += Integer.valueOf ( map.get ( "total" ).toString () );
                        alreadDoneCount += Integer.valueOf ( map.get ( "total" ).toString () );
                        break;
                }
                countTotal += Integer.valueOf ( map.get ( "total" ).toString () );
            }
            rsMap.put ( "alreadSendCount", alreadSendCount );
            rsMap.put ( "alreadDoneCount", alreadDoneCount );
            rsMap.put ( "countTotal", countTotal );
        }
        if (type == 2) {
            /**----- 待分配 -----*/
            //待分配 条件
            conditionSql.append ( " WHERE " );
            conditionSql.append ( " ( " );
            conditionSql.append ( " 	(ip.company_had_area_eg = 1 AND ip.state IN ('" ).append ( StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY ).append ( "','" ).append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_REFUSED ).append ( "')) " );
            conditionSql.append ( " 	OR " );
            conditionSql.append ( " 	(ip.company_had_area_eg = 0 AND ip.state IN ('" ).append ( StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY ).append ( "','" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED ).append ( "')) " );
            conditionSql.append ( " ) " );
            conditionSql.append ( " AND ip.company = '" ).append ( company ).append ( "' " );//只查询指派到自己单位的
//            if (null != idsList && idsList.size () > 0) {
//                conditionSql.append ( " AND ip.id IN (" );
//                for (int i = 0; i < idsList.size (); i++) {
//                    if (i == idsList.size () - 1) {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'" );
//                    } else {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'," );
//                    }
//                }
//                conditionSql.append ( " ) " );
//            } else {
//                conditionSql.append ( " AND 1 != 1" );
//            }
            areaMapList = super.findForJdbc ( citySqlpart1.toString () + conditionSql.toString () + citySqlpart2.toString () );
            planMonthMapList = super.findForJdbc ( planQuarterSqlpart1.toString () + conditionSql.toString () + planQuarterSqlpart2.toString () );
            rsMap.put ( "areaMapList_todo", areaMapList );
            rsMap.put ( "planMonthMapList_todo", planMonthMapList );

            if (!area.equals ( "" )) {
                conditionSql.append ( " AND tt.id ='" ).append ( area ).append ( "' " );
            }
            if (StringUtil.isNotEmpty ( planYear ) && StringUtil.isNotEmpty ( planMonth )) {
                conditionSql.append ( " AND YEAR(ip.ip_plan_date) ='" ).append ( planYear ).append ( "' " );
                conditionSql.append ( " AND MONTH(ip.ip_plan_date) ='" ).append ( planMonth ).append ( "' " );
            }
            if (!esSn.equals ( "" )) {
                conditionSql.append ( " AND es.sn ='" ).append ( esSn ).append ( "' " );
            }
            if (!cmId.equals ( "" )) {
                conditionSql.append ( " AND cm.id ='" ).append ( cmId ).append ( "' " );
            }
            List<Map<String, Object>> tpIpMapList_todo = new ArrayList<Map<String, Object>> ();
            List<Map<String, Object>> groupMap_todo = super.findForJdbc ( groupSqlpart1.toString () + conditionSql.toString () + groupSqlpart2.toString () );
            List<Map<String, Object>> detailMap_todo = super.findForJdbc ( detailSql.toString () + conditionSql.toString () );
            //合并
            for (Map<String, Object> cmM : groupMap_todo) {
                if (null != cmM) {
                    Map<String, Object> m = new HashMap<String, Object> ();
                    m.put ( "cmM", cmM );
                    List<Map<String, Object>> dtMapList = new ArrayList<Map<String, Object>> ();
                    for (Map<String, Object> dtM : detailMap_todo) {
                        if (null != dtM.get ( "cmId" ) && dtM.get ( "cmId" ).equals ( cmM.get ( "cmId" ) )) {
                            dtMapList.add ( dtM );
                        }
                        m.put ( "dtMapList", dtMapList );//是不是null 都put进去，防止页面取值出现问题
                    }
                    tpIpMapList_todo.add ( m );
                }
            }

            rsMap.put ( "tpIpMapList_todo", tpIpMapList_todo );
        }
        /**------ 待分配---end--*/
        /**------ 已分配-----*/
        if (type == 3) {
//            StringBuffer sql = new StringBuffer ();//3个月内 。这个比对的时间只好拿 巡检记录的时间
//            sql.append ( " SELECT " );
//            sql.append ( " 	DISTINCT pr.bus_id AS busId " );
//            sql.append ( " FROM " );
//            sql.append ( " 	zy_plan_record pr " );
//            sql.append ( " WHERE pr.create_by = '" ).append ( user.getUserName () ).append ( "' " );
//            sql.append ( " AND pr.plan_state = '" ).append ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED ).append ( "' " );
//            sql.append ( " AND DATE_SUB(CURDATE(), INTERVAL 3 MONTH) <= pr.create_date " );
//            List<Map<String, Object>> idsMapList = super.findForJdbc ( sql.toString () );
//            if (null != idsMapList && idsMapList.size () > 0) {
//                for (int i = 0; i < idsMapList.size (); i++) {
//                    if (null != idsMapList.get ( i )) {
//                        idsList.add ( idsMapList.get ( i ).get ( "busId" ).toString () );
//                    }
//                }
//            }
            conditionSql = new StringBuffer ();
            conditionSql.append ( " WHERE " );
            conditionSql.append ( " ip.state IN (" );
            conditionSql.append ( "'" ).append ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED ).append ( "'," );
            conditionSql.append ( "'" ).append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_ASSIGNED ).append ( "'," );
            conditionSql.append ( "'" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED ).append ( "'," );
            conditionSql.append ( "'" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT ).append ( "'," );
            conditionSql.append ( "'" ).append ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE ).append ( "'" );
            conditionSql.append ( ") " );
            conditionSql.append ( " AND ip.company = '" ).append ( company ).append ( "' " );//只查询指派到自己单位的
            conditionSql.append(" and DATE_SUB(CURDATE(), INTERVAL 3 MONTH) <= ip.ip_plan_date ");//3个月内的

//            if (null != idsList && idsList.size () > 0) {
//                conditionSql.append ( " AND ip.id IN (" );
//                for (int i = 0; i < idsList.size (); i++) {
//                    if (i == idsList.size () - 1) {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'" );
//                    } else {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'," );
//                    }
//                }
//                conditionSql.append ( " ) " );
//            } else {
//                conditionSql.append ( " AND 1 != 1" );
//            }

            areaMapList = super.findForJdbc ( citySqlpart1.toString () + conditionSql.toString () + citySqlpart2.toString () );
            planMonthMapList = super.findForJdbc ( planQuarterSqlpart1.toString () + conditionSql.toString () + planQuarterSqlpart2.toString () );
            rsMap.put ( "areaMapList_already_send", areaMapList );
            rsMap.put ( "planMonthMapList_already_send", planMonthMapList );

            if (!area.equals ( "" )) {
                conditionSql.append ( " AND tt.id ='" ).append ( area ).append ( "' " );
            }
            if (StringUtil.isNotEmpty ( planYear ) && StringUtil.isNotEmpty ( planMonth )) {
                conditionSql.append ( " AND YEAR(ip.ip_plan_date) ='" ).append ( planYear ).append ( "' " );
                conditionSql.append ( " AND MONTH(ip.ip_plan_date) ='" ).append ( planMonth ).append ( "' " );
            }
            if (!esSn.equals ( "" )) {
                conditionSql.append ( " AND es.sn ='" ).append ( esSn ).append ( "' " );
            }
            if (!cmId.equals ( "" )) {
                conditionSql.append ( " AND cm.id ='" ).append ( cmId ).append ( "' " );
            }
            List<Map<String, Object>> tpIpMapList_already_send = new ArrayList<Map<String, Object>> ();
            List<Map<String, Object>> groupMap_already_send = super.findForJdbc ( groupSqlpart1.toString () + conditionSql.toString () + groupSqlpart2.toString () );
            List<Map<String, Object>> detailMap_already_send = super.findForJdbc ( detailSql.toString () + conditionSql.toString () );
            //合并
            for (Map<String, Object> cmM : groupMap_already_send) {
                if (null != cmM) {
                    Map<String, Object> m = new HashMap<String, Object> ();
                    m.put ( "cmM", cmM );
                    List<Map<String, Object>> dtMapList = new ArrayList<Map<String, Object>> ();
                    for (Map<String, Object> dtM : detailMap_already_send) {
                        if (dtM.get ( "state" ).toString ().equals ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE )) {
                            dtM.put ( "isDone", "1" );
                        }
                        if (null != dtM.get ( "cmId" ) && dtM.get ( "cmId" ).equals ( cmM.get ( "cmId" ) )) {
                            dtMapList.add ( dtM );
                        }
                        m.put ( "dtMapList", dtMapList );//是不是null 都put进去，防止页面取值出现问题
                    }
                    tpIpMapList_already_send.add ( m );
                }
            }

            rsMap.put ( "tpIpMapList_already_send", tpIpMapList_already_send );
        }
        /**------ 已分配---end--*/
        /**------ 已拒绝-----*/
        if (type == 4) {
            conditionSql = new StringBuffer ();
            conditionSql.append ( " WHERE " );
            conditionSql.append ( " ip.state = '" ).append ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_REFUSED ).append ( "' " );
            conditionSql.append ( " AND ip.company = '" ).append ( company ).append ( "' " );//只查询指派到自己单位的
//            if (null != idsList && idsList.size () > 0) {
//                conditionSql.append ( " AND ip.id IN (" );
//                for (int i = 0; i < idsList.size (); i++) {
//                    if (i == idsList.size () - 1) {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'" );
//                    } else {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'," );
//                    }
//                }
//                conditionSql.append ( " ) " );
//            } else {
//                conditionSql.append ( " AND 1 != 1" );
//            }

            areaMapList = super.findForJdbc ( citySqlpart1.toString () + conditionSql.toString () + citySqlpart2.toString () );
            planMonthMapList = super.findForJdbc ( planQuarterSqlpart1.toString () + conditionSql.toString () + planQuarterSqlpart2.toString () );
            rsMap.put ( "areaMapList_already_refuse", areaMapList );
            rsMap.put ( "planMonthMapList_already_refuse", planMonthMapList );

            if (!area.equals ( "" )) {
                conditionSql.append ( " AND tt.id ='" ).append ( area ).append ( "' " );
            }
            if (StringUtil.isNotEmpty ( planYear ) && StringUtil.isNotEmpty ( planMonth )) {
                conditionSql.append ( " AND YEAR(ip.ip_plan_date) ='" ).append ( planYear ).append ( "' " );
                conditionSql.append ( " AND MONTH(ip.ip_plan_date) ='" ).append ( planMonth ).append ( "' " );
            }
            if (!esSn.equals ( "" )) {
                conditionSql.append ( " AND es.sn ='" ).append ( esSn ).append ( "' " );
            }
            if (!cmId.equals ( "" )) {
                conditionSql.append ( " AND cm.id ='" ).append ( cmId ).append ( "' " );
            }
            List<Map<String, Object>> tpIpMapList_already_refuse = new ArrayList<Map<String, Object>> ();
            List<Map<String, Object>> groupMap_already_refuse = super.findForJdbc ( groupSqlpart1.toString () + conditionSql.toString () + groupSqlpart2.toString () );
            List<Map<String, Object>> detailMap_already_refuse = super.findForJdbc ( detailSql.toString () + conditionSql.toString () );
            //合并
            for (Map<String, Object> cmM : groupMap_already_refuse) {
                if (null != cmM) {
                    Map<String, Object> m = new HashMap<String, Object> ();
                    m.put ( "cmM", cmM );
                    List<Map<String, Object>> dtMapList = new ArrayList<Map<String, Object>> ();
                    for (Map<String, Object> dtM : detailMap_already_refuse) {
                        if (null != dtM.get ( "cmId" ) && dtM.get ( "cmId" ).equals ( cmM.get ( "cmId" ) )) {
                            dtMapList.add ( dtM );
                        }
                        m.put ( "dtMapList", dtMapList );//是不是null 都put进去，防止页面取值出现问题
                    }
                    tpIpMapList_already_refuse.add ( m );
                }
            }

            rsMap.put ( "tpIpMapList_already_refuse", tpIpMapList_already_refuse );
        }
        /**------ 已拒绝---end--*/

        return rsMap;
    }

    @Override
    public Map<String, Object> queryAppIpAegList(int type, String area, String planYear, String planMonth, String esSn, String cmId) {
        Map<String, Object> rsMap = new HashMap<String, Object> ();
        TSUser user = ResourceUtil.getSessionUserName ();
        //影院分组
        StringBuffer groupSqlpart1 = new StringBuffer ();
        groupSqlpart1.append ( " SELECT " );
        groupSqlpart1.append ( " 	IFNULL(cm.id,'无') AS cmId, " );
        groupSqlpart1.append ( " 	IFNULL(cm.`name`,'无') AS cmName, " );
        groupSqlpart1.append ( " 	ct.`name` AS cmCtIpName, " );
        groupSqlpart1.append ( " 	ct.cellphone1, " );
        groupSqlpart1.append ( " 	ct.cellphone2, " );
        groupSqlpart1.append ( " 	IFNULL(cm.address,'无') AS address " );
        groupSqlpart1.append ( " FROM " );
        groupSqlpart1.append ( " 	zy_inspection_plan ip " );
        groupSqlpart1.append ( " LEFT JOIN zy_equipment_spare es ON es.id = ip.equipment_spare_id " );
        groupSqlpart1.append ( " LEFT JOIN zy_cinema cm ON cm.id = es.belong_cinema_id " );
        groupSqlpart1.append ( " LEFT JOIN t_s_territory tt ON tt.id = cm.province " );
        groupSqlpart1.append ( " LEFT JOIN zy_contacts ct ON ct.belong_cinema = cm.id " );
        groupSqlpart1.append ( " 	AND ct.state = '" ).append ( StaticValue.DIC_ENGINEER_STATE_ONJOB ).append ( "' " );
        groupSqlpart1.append ( " 	AND ct.is_delete = 0 " );
        groupSqlpart1.append ( " 	AND ct.type = '" ).append ( StaticValue.DIC_CONTACT_TYPE_CINEMA_CONTACT ).append ( "' " );
        groupSqlpart1.append ( " 	AND ct.con_business LIKE '%" ).append ( StaticValue.DIC_LINK_BUSINESS_INSPECTION ).append ( "%' " );
        StringBuffer groupSqlpart2 = new StringBuffer ();
        groupSqlpart2.append ( " GROUP BY " );
        groupSqlpart2.append ( "	cm.`name` " );
        //巡检计划
        StringBuffer detailSql = new StringBuffer ();
        detailSql.append ( " SELECT " );
        detailSql.append ( " 	ip.id AS ipId, " );
        detailSql.append ( " 	ip.state, " );
        detailSql.append ( "	CASE ip.state WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY ).append ( "' THEN '1' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED ).append ( "' THEN '2' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_REFUSED ).append ( "' THEN '3' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_ASSIGNED ).append ( "' THEN '4' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_REFUSED ).append ( "' THEN '5' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED ).append ( "' THEN '6' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED ).append ( "' THEN '7' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT ).append ( "' THEN '8' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE ).append ( "' THEN '9' END AS ipState, " );
        detailSql.append ( " 	es.sn, " );
        detailSql.append ( " 	ip.plan_id AS planId, " );
        detailSql.append ( " 	MONTH(ip.ip_plan_date) AS ipMonth, " );
        detailSql.append ( " 	DATE_FORMAT(ip.create_date,'%Y-%m-%d') AS createDate, " );
        detailSql.append ( " 	IFNULL(cm.id,'无') AS cmId " );
        detailSql.append ( " FROM " );
        detailSql.append ( " 	zy_inspection_plan ip " );
//        detailSql.append(" LEFT JOIN t_s_typegroup tg ON tg.typegroupcode = '").append(StaticValue.DIC_PLAN_INSPECTION_QUARTER).append("' ");
//        detailSql.append(" LEFT JOIN t_s_type tp ON tp.typecode = ip.plan_quarter AND tg.ID = tp.typegroupid ");
        detailSql.append ( " LEFT JOIN zy_equipment_spare es ON es.id = ip.equipment_spare_id " );
        detailSql.append ( " LEFT JOIN zy_cinema cm ON cm.id = es.belong_cinema_id " );
        detailSql.append ( " LEFT JOIN t_s_territory tt ON tt.id = cm.province " );

        //列表页上方 - 地区分组sql
        StringBuffer citySqlpart1 = new StringBuffer ();
        citySqlpart1.append ( " SELECT " );
        citySqlpart1.append ( " 	tt.ID AS id, " );
        citySqlpart1.append ( " 	tt.territoryname, " );
        citySqlpart1.append ( " 	count(ip.id) AS total " );
        citySqlpart1.append ( " FROM " );
        citySqlpart1.append ( " 	zy_inspection_plan ip " );
        citySqlpart1.append ( " LEFT JOIN zy_equipment_spare es ON es.id = ip.equipment_spare_id " );
        citySqlpart1.append ( " LEFT JOIN zy_cinema cm ON cm.id = es.belong_cinema_id " );
        citySqlpart1.append ( " LEFT JOIN t_s_territory tt ON tt.id = cm.province " );
        StringBuffer citySqlpart2 = new StringBuffer ();
        citySqlpart2.append ( " GROUP BY " );
        citySqlpart2.append ( " 	tt.ID " );
        citySqlpart2.append ( " ORDER BY " );
        citySqlpart2.append ( " 	tt.territorysort " );

        //列表上方 - 巡检年月分组sql
        StringBuffer planQuarterSqlpart1 = new StringBuffer ();
        planQuarterSqlpart1.append ( " SELECT " );
//        planQuarterSqlpart1.append(" 	MONTH(ip.ip_plan_date) AS planMonth, ");
        planQuarterSqlpart1.append ( " 	DATE_FORMAT(ip.ip_plan_date,'%Y年-%m月') AS planYearMonth, " );
        planQuarterSqlpart1.append ( "	YEAR(ip.ip_plan_date) AS planYear, MONTH(ip.ip_plan_date) AS planMonth, " );
        planQuarterSqlpart1.append ( " 	count(ip.id) AS total " );
        planQuarterSqlpart1.append ( " FROM " );
        planQuarterSqlpart1.append ( " 	zy_inspection_plan ip " );
        planQuarterSqlpart1.append ( " LEFT JOIN zy_equipment_spare es ON es.id = ip.equipment_spare_id " );
        planQuarterSqlpart1.append ( " LEFT JOIN zy_cinema cm ON cm.id = es.belong_cinema_id " );
        planQuarterSqlpart1.append ( " LEFT JOIN t_s_territory tt ON tt.id = cm.province " );

        StringBuffer planQuarterSqlpart2 = new StringBuffer ();
        planQuarterSqlpart2.append ( " GROUP BY " );
        planQuarterSqlpart2.append ( " 	planYearMonth " );
        planQuarterSqlpart2.append ( " ORDER BY " );
        planQuarterSqlpart2.append ( " 	planYearMonth " );
        List<Map<String, Object>> areaMapList;
        List<Map<String, Object>> planMonthMapList;
        StringBuffer conditionSql = new StringBuffer ();
        List<String> idsList = zyWorkFlowService.queryUserProcess ( user.getUserName (), StaticValue.P_PROCESS_INSPECTION, true, null );
        ZyEngineerEntity engineer = systemService.findUniqueByProperty ( ZyEngineerEntity.class, "tsBaseUser.id", user.getId () );
        String engineerId = engineer.getId ();
        if (type == 1) {

            /**----- 待分配 -----*/
            //待分配 条件
            conditionSql.append ( " WHERE " );
            conditionSql.append ( " ip.state IN(" +
                    "'" ).append ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED ).append ( "'," +
                    "'" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED ).append ( "'" +
                    ")" );
            conditionSql.append(" AND ip.aeg_id = '").append(engineerId).append("' ");//只查询指派到自己的
//            if (null != idsList && idsList.size () > 0) {
//                conditionSql.append ( " AND ip.id IN (" );
//                for (int i = 0; i < idsList.size (); i++) {
//                    if (i == idsList.size () - 1) {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'" );
//                    } else {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'," );
//                    }
//                }
//                conditionSql.append ( " ) " );
//            } else {
//                conditionSql.append ( " AND 1 != 1" );
//            }
            System.out.println ( citySqlpart1.toString () + conditionSql.toString () + citySqlpart2.toString () );
            System.out.println ( planQuarterSqlpart1.toString () + conditionSql.toString () + planQuarterSqlpart2.toString () );
            areaMapList = super.findForJdbc ( citySqlpart1.toString () + conditionSql.toString () + citySqlpart2.toString () );
            planMonthMapList = super.findForJdbc ( planQuarterSqlpart1.toString () + conditionSql.toString () + planQuarterSqlpart2.toString () );
            rsMap.put ( "areaMapList_todo", areaMapList );
            rsMap.put ( "planMonthMapList_todo", planMonthMapList );


            if (!area.equals ( "" )) {
                conditionSql.append ( " AND tt.id ='" ).append ( area ).append ( "' " );
            }
            if (StringUtil.isNotEmpty ( planYear ) && StringUtil.isNotEmpty ( planMonth )) {
                conditionSql.append ( " AND YEAR(ip.ip_plan_date) ='" ).append ( planYear ).append ( "' " );
                conditionSql.append ( " AND MONTH(ip.ip_plan_date) ='" ).append ( planMonth ).append ( "' " );
            }
            if (!esSn.equals ( "" )) {
                conditionSql.append ( " AND es.sn ='" ).append ( esSn ).append ( "' " );
            }
            if (!cmId.equals ( "" )) {
                conditionSql.append ( " AND cm.id ='" ).append ( cmId ).append ( "' " );
            }
            List<Map<String, Object>> tpIpMapList_todo = new ArrayList<Map<String, Object>> ();
            System.out.println ( groupSqlpart1.toString () + conditionSql.toString () + groupSqlpart2.toString () );
            System.out.println ( detailSql.toString () + conditionSql.toString () );
            List<Map<String, Object>> groupMap_todo = super.findForJdbc ( groupSqlpart1.toString () + conditionSql.toString () + groupSqlpart2.toString () );
            List<Map<String, Object>> detailMap_todo = super.findForJdbc ( detailSql.toString () + conditionSql.toString () );
            //合并
            for (Map<String, Object> cmM : groupMap_todo) {
                if (null != cmM) {
                    Map<String, Object> m = new HashMap<String, Object> ();
                    m.put ( "cmM", cmM );
                    List<Map<String, Object>> dtMapList = new ArrayList<Map<String, Object>> ();
                    for (Map<String, Object> dtM : detailMap_todo) {
                        if (null != dtM.get ( "cmId" ) && dtM.get ( "cmId" ).equals ( cmM.get ( "cmId" ) )) {
                            dtMapList.add ( dtM );
                        }
                        m.put ( "dtMapList", dtMapList );//是不是null 都put进去，防止页面取值出现问题
                    }
                    tpIpMapList_todo.add ( m );
                }
            }

            rsMap.put ( "tpIpMapList_todo", tpIpMapList_todo );
        }
        /**------ 待分配---end--*/
        /**------ 已分配-----*/
        if (type == 2) {
//            StringBuffer sql = new StringBuffer ();//3个月内 。这个比对的时间只好拿 巡检记录的时间
//            sql.append ( " SELECT " );
//            sql.append ( " 	DISTINCT pr.bus_id AS busId " );
//            sql.append ( " FROM " );
//            sql.append ( " 	zy_plan_record pr " );
//            sql.append ( " WHERE pr.create_by = '" ).append ( user.getUserName () ).append ( "' " );
//            sql.append ( " AND pr.plan_state = '" ).append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_ASSIGNED ).append ( "' " );
//            sql.append ( " AND DATE_SUB(CURDATE(), INTERVAL 1 DAY) <= pr.create_date " );
//            List<Map<String, Object>> idsMapList = super.findForJdbc ( sql.toString () );
//            if (null != idsMapList && idsMapList.size () > 0) {
//                for (int i = 0; i < idsMapList.size (); i++) {
//                    if (null != idsMapList.get ( i )) {
//                        idsList.add ( idsMapList.get ( i ).get ( "busId" ).toString () );
//                    }
//                }
//            }
            conditionSql = new StringBuffer ();
            conditionSql.append ( " WHERE " );
            conditionSql.append ( " ip.state IN (" );
            conditionSql.append ( "'" ).append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_ASSIGNED ).append ( "'," );
            conditionSql.append ( "'" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED ).append ( "'," );
            conditionSql.append ( "'" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT ).append ( "'," );
            conditionSql.append ( "'" ).append ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE ).append ( "'" );
            conditionSql.append ( ") " );
            conditionSql.append(" AND ip.aeg_id = '").append(engineerId).append("' ");//只查询指派到自己的
            conditionSql.append(" and DATE_SUB(CURDATE(), INTERVAL 3 MONTH) <= ip.ip_plan_date ");
//            if (null != idsList && idsList.size () > 0) {
//                conditionSql.append ( " AND ip.id IN (" );
//                for (int i = 0; i < idsList.size (); i++) {
//                    if (i == idsList.size () - 1) {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'" );
//                    } else {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'," );
//                    }
//                }
//                conditionSql.append ( " ) " );
//            } else {
//                conditionSql.append ( " AND 1 != 1" );
//            }

            areaMapList = super.findForJdbc ( citySqlpart1.toString () + conditionSql.toString () + citySqlpart2.toString () );
            planMonthMapList = super.findForJdbc ( planQuarterSqlpart1.toString () + conditionSql.toString () + planQuarterSqlpart2.toString () );
            rsMap.put ( "areaMapList_already_send", areaMapList );
            rsMap.put ( "planMonthMapList_already_send", planMonthMapList );

            if (!area.equals ( "" )) {
                conditionSql.append ( " AND tt.id ='" ).append ( area ).append ( "' " );
            }
            if (StringUtil.isNotEmpty ( planYear ) && StringUtil.isNotEmpty ( planMonth )) {
                conditionSql.append ( " AND YEAR(ip.ip_plan_date) ='" ).append ( planYear ).append ( "' " );
                conditionSql.append ( " AND MONTH(ip.ip_plan_date) ='" ).append ( planMonth ).append ( "' " );
            }
            if (!esSn.equals ( "" )) {
                conditionSql.append ( " AND es.sn ='" ).append ( esSn ).append ( "' " );
            }
            if (!cmId.equals ( "" )) {
                conditionSql.append ( " AND cm.id ='" ).append ( cmId ).append ( "' " );
            }
            List<Map<String, Object>> tpIpMapList_already_send = new ArrayList<Map<String, Object>> ();
            List<Map<String, Object>> groupMap_already_send = super.findForJdbc ( groupSqlpart1.toString () + conditionSql.toString () + groupSqlpart2.toString () );
            List<Map<String, Object>> detailMap_already_send = super.findForJdbc ( detailSql.toString () + conditionSql.toString () );
            //合并
            for (Map<String, Object> cmM : groupMap_already_send) {
                if (null != cmM) {
                    Map<String, Object> m = new HashMap<String, Object> ();
                    m.put ( "cmM", cmM );
                    List<Map<String, Object>> dtMapList = new ArrayList<Map<String, Object>> ();
                    for (Map<String, Object> dtM : detailMap_already_send) {
                        if (dtM.get ( "state" ).toString ().equals ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE )) {
                            dtM.put ( "isDone", "1" );
                        }
                        if (null != dtM.get ( "cmId" ) && dtM.get ( "cmId" ).equals ( cmM.get ( "cmId" ) )) {
                            dtMapList.add ( dtM );
                        }
                        m.put ( "dtMapList", dtMapList );//是不是null 都put进去，防止页面取值出现问题
                    }
                    tpIpMapList_already_send.add ( m );
                }
            }

            rsMap.put ( "tpIpMapList_already_send", tpIpMapList_already_send );
        }
        /**------ 已分配---end--*/
        /**------ 已拒绝-----*/
        if (type == 3) {
            conditionSql = new StringBuffer ();
            conditionSql.append ( " WHERE " );
            conditionSql.append ( " ip.state = '" ).append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_REFUSED ).append ( "' " );
            conditionSql.append(" AND ip.aeg_id = '").append(engineerId).append("' ");//只查询指派到自己的
//            if (null != idsList && idsList.size () > 0) {
//                conditionSql.append ( " AND ip.id IN (" );
//                for (int i = 0; i < idsList.size (); i++) {
//                    if (i == idsList.size () - 1) {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'" );
//                    } else {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'," );
//                    }
//                }
//                conditionSql.append ( " ) " );
//            } else {
//                conditionSql.append ( " AND 1 != 1" );
//            }

            areaMapList = super.findForJdbc ( citySqlpart1.toString () + conditionSql.toString () + citySqlpart2.toString () );
            planMonthMapList = super.findForJdbc ( planQuarterSqlpart1.toString () + conditionSql.toString () + planQuarterSqlpart2.toString () );
            rsMap.put ( "areaMapList_already_refuse", areaMapList );
            rsMap.put ( "planMonthMapList_already_refuse", planMonthMapList );

            if (!area.equals ( "" )) {
                conditionSql.append ( " AND tt.id ='" ).append ( area ).append ( "' " );
            }
            if (StringUtil.isNotEmpty ( planYear ) && StringUtil.isNotEmpty ( planMonth )) {
                conditionSql.append ( " AND YEAR(ip.ip_plan_date) ='" ).append ( planYear ).append ( "' " );
                conditionSql.append ( " AND MONTH(ip.ip_plan_date) ='" ).append ( planMonth ).append ( "' " );
            }
            if (!esSn.equals ( "" )) {
                conditionSql.append ( " AND es.sn ='" ).append ( esSn ).append ( "' " );
            }
            if (!cmId.equals ( "" )) {
                conditionSql.append ( " AND cm.id ='" ).append ( cmId ).append ( "' " );
            }
            List<Map<String, Object>> tpIpMapList_already_refuse = new ArrayList<Map<String, Object>> ();
            List<Map<String, Object>> groupMap_already_refuse = super.findForJdbc ( groupSqlpart1.toString () + conditionSql.toString () + groupSqlpart2.toString () );
            List<Map<String, Object>> detailMap_already_refuse = super.findForJdbc ( detailSql.toString () + conditionSql.toString () );
            //合并
            for (Map<String, Object> cmM : groupMap_already_refuse) {
                if (null != cmM) {
                    Map<String, Object> m = new HashMap<String, Object> ();
                    m.put ( "cmM", cmM );
                    List<Map<String, Object>> dtMapList = new ArrayList<Map<String, Object>> ();
                    for (Map<String, Object> dtM : detailMap_already_refuse) {
                        if (null != dtM.get ( "cmId" ) && dtM.get ( "cmId" ).equals ( cmM.get ( "cmId" ) )) {
                            dtMapList.add ( dtM );
                        }
                        m.put ( "dtMapList", dtMapList );//是不是null 都put进去，防止页面取值出现问题
                    }
                    tpIpMapList_already_refuse.add ( m );
                }
            }

            rsMap.put ( "tpIpMapList_already_refuse", tpIpMapList_already_refuse );
        }
        /**------ 已拒绝---end--*/

        return rsMap;
    }


    @Override
    public Map<String, Object> queryAppIpEgList(int type, String area, String planYear, String planMonth, String esSn, String cmId) {
        Map<String, Object> rsMap = new HashMap<String, Object> ();
        TSUser user = ResourceUtil.getSessionUserName ();
        //影院分组
        StringBuffer groupSqlpart1 = new StringBuffer ();
        groupSqlpart1.append ( " SELECT " );
        groupSqlpart1.append ( " 	IFNULL(cm.id,'无') AS cmId, " );
        groupSqlpart1.append ( " 	IFNULL(cm.`name`,'无') AS cmName, " );
        groupSqlpart1.append ( " 	ct.`name` AS cmCtIpName, " );
        groupSqlpart1.append ( " 	ct.cellphone1, " );
        groupSqlpart1.append ( " 	ct.cellphone2, " );
        groupSqlpart1.append ( " 	IFNULL(cm.address,'无') AS address " );
        groupSqlpart1.append ( " FROM " );
        groupSqlpart1.append ( " 	zy_inspection_plan ip " );
        groupSqlpart1.append ( " LEFT JOIN zy_equipment_spare es ON es.id = ip.equipment_spare_id " );
        groupSqlpart1.append ( " LEFT JOIN zy_cinema cm ON cm.id = es.belong_cinema_id " );
        groupSqlpart1.append ( " LEFT JOIN t_s_territory tt ON tt.id = cm.province " );
        groupSqlpart1.append ( " LEFT JOIN zy_contacts ct ON ct.belong_cinema = cm.id " );
        groupSqlpart1.append ( " 	AND ct.state = '" ).append ( StaticValue.DIC_ENGINEER_STATE_ONJOB ).append ( "' " );
        groupSqlpart1.append ( " 	AND ct.is_delete = 0 " );
        groupSqlpart1.append ( " 	AND ct.type = '" ).append ( StaticValue.DIC_CONTACT_TYPE_CINEMA_CONTACT ).append ( "' " );
        groupSqlpart1.append ( " 	AND ct.con_business LIKE '%" ).append ( StaticValue.DIC_LINK_BUSINESS_INSPECTION ).append ( "%' " );
        StringBuffer groupSqlpart2 = new StringBuffer ();
        groupSqlpart2.append ( " GROUP BY " );
        groupSqlpart2.append ( "	cm.`name` " );
        //巡检计划
        StringBuffer detailSql = new StringBuffer ();
        detailSql.append ( " SELECT " );
        detailSql.append ( " 	ip.id AS ipId, DATE_FORMAT(ip.order_begin_time,'%Y-%m-%d') AS orderBeginTime, DATE_FORMAT(ip.order_end_time,'%Y-%m-%d') AS orderEndTime, " +
                "DATE_FORMAT(ip.engineer_order_time,'%Y-%m-%d') AS engineerOrderTime, " );
        detailSql.append ( " 	ip.state, " );
        detailSql.append ( "	CASE ip.state WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY ).append ( "' THEN '1' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED ).append ( "' THEN '2' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_REFUSED ).append ( "' THEN '3' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_ASSIGNED ).append ( "' THEN '4' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_REFUSED ).append ( "' THEN '5' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED ).append ( "' THEN '6' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED ).append ( "' THEN '7' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT ).append ( "' THEN '8' " );
        detailSql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE ).append ( "' THEN '9' END AS ipState, " );
        detailSql.append ( " 	es.sn, " );
        detailSql.append ( " 	ip.plan_id AS planId, " );
        detailSql.append ( " 	MONTH(ip.ip_plan_date) AS ipMonth, " );
        detailSql.append ( " 	DATE_FORMAT(ip.create_date,'%Y-%m-%d') AS createDate, " );
        detailSql.append ( " 	IFNULL(cm.id,'无') AS cmId " );
        detailSql.append ( " FROM " );
        detailSql.append ( " 	zy_inspection_plan ip " );
//        detailSql.append(" LEFT JOIN t_s_typegroup tg ON tg.typegroupcode = '").append(StaticValue.DIC_PLAN_INSPECTION_QUARTER).append("' ");
//        detailSql.append(" LEFT JOIN t_s_type tp ON tp.typecode = ip.plan_quarter AND tg.ID = tp.typegroupid ");
        detailSql.append ( " LEFT JOIN zy_equipment_spare es ON es.id = ip.equipment_spare_id " );
        detailSql.append ( " LEFT JOIN zy_cinema cm ON cm.id = es.belong_cinema_id " );
        detailSql.append ( " LEFT JOIN t_s_territory tt ON tt.id = cm.province " );

        //列表页上方 - 地区分组sql
        StringBuffer citySqlpart1 = new StringBuffer ();
        citySqlpart1.append ( " SELECT " );
        citySqlpart1.append ( " 	tt.ID AS id, " );
        citySqlpart1.append ( " 	tt.territoryname, " );
        citySqlpart1.append ( " 	count(ip.id) AS total " );
        citySqlpart1.append ( " FROM " );
        citySqlpart1.append ( " 	zy_inspection_plan ip " );
        citySqlpart1.append ( " LEFT JOIN zy_equipment_spare es ON es.id = ip.equipment_spare_id " );
        citySqlpart1.append ( " LEFT JOIN zy_cinema cm ON cm.id = es.belong_cinema_id " );
        citySqlpart1.append ( " LEFT JOIN t_s_territory tt ON tt.id = cm.province " );
        StringBuffer citySqlpart2 = new StringBuffer ();
        citySqlpart2.append ( " GROUP BY " );
        citySqlpart2.append ( " 	tt.ID " );
        citySqlpart2.append ( " ORDER BY " );
        citySqlpart2.append ( " 	tt.territorysort " );

        //列表上方 - 季度分组sql
        StringBuffer planQuarterSqlpart1 = new StringBuffer ();
        planQuarterSqlpart1.append ( " SELECT " );
//      planQuarterSqlpart1.append(" 	MONTH(ip.ip_plan_date) AS planMonth, ");
        planQuarterSqlpart1.append ( " 	DATE_FORMAT(ip.ip_plan_date,'%Y年-%m月') AS planYearMonth, " );
        planQuarterSqlpart1.append ( "	YEAR(ip.ip_plan_date) AS planYear, MONTH(ip.ip_plan_date) AS planMonth, " );
        planQuarterSqlpart1.append ( " 	count(ip.id) AS total " );
        planQuarterSqlpart1.append ( " FROM " );
        planQuarterSqlpart1.append ( " 	zy_inspection_plan ip " );
        planQuarterSqlpart1.append ( " LEFT JOIN zy_equipment_spare es ON es.id = ip.equipment_spare_id " );
        planQuarterSqlpart1.append ( " LEFT JOIN zy_cinema cm ON cm.id = es.belong_cinema_id " );
        planQuarterSqlpart1.append ( " LEFT JOIN t_s_territory tt ON tt.id = cm.province " );

        StringBuffer planQuarterSqlpart2 = new StringBuffer ();
        planQuarterSqlpart2.append ( " GROUP BY " );
        planQuarterSqlpart2.append ( " 	planYearMonth " );
        planQuarterSqlpart2.append ( " ORDER BY " );
        planQuarterSqlpart2.append ( " 	planYearMonth " );
        List<Map<String, Object>> areaMapList;
        List<Map<String, Object>> planMonthMapList;
        StringBuffer conditionSql = new StringBuffer ();
        List<String> idsList = zyWorkFlowService.queryUserProcess ( user.getUserName (), StaticValue.P_PROCESS_INSPECTION, true, StaticValue.P_PROCESS_INSPECTION_TASKNODE03_2 );
        ZyEngineerEntity engineer = systemService.findUniqueByProperty ( ZyEngineerEntity.class, "tsBaseUser.id", user.getId () );
        String engineerId = engineer.getId ();
        if (type == 1) {

            /**----- 待处理 -----*/
            //待处理 条件
            conditionSql.append ( " WHERE " );
            conditionSql.append ( " ( " );
            conditionSql.append ( "	(ip.company_had_area_eg = 1 AND ip.state IN ('" ).append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_ASSIGNED ).append ( "') ) " );
            conditionSql.append ( " 	OR " );
            conditionSql.append ( " 	(ip.company_had_area_eg = 0 AND ip.state IN ('" ).append ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED ).append ( "') ) " );
            conditionSql.append ( " ) " );
            conditionSql.append(" AND ip.engineer = '").append(engineerId).append("' ");//只查询指派到自己的
//            if (null != idsList && idsList.size () > 0) {
//                conditionSql.append ( " AND ip.id IN (" );
//                for (int i = 0; i < idsList.size (); i++) {
//                    if (i == idsList.size () - 1) {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'" );
//                    } else {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'," );
//                    }
//                }
//                conditionSql.append ( " ) " );
//            } else {
//                conditionSql.append ( " AND 1 != 1" );
//            }
            areaMapList = super.findForJdbc ( citySqlpart1.toString () + conditionSql.toString () + citySqlpart2.toString () );
            planMonthMapList = super.findForJdbc ( planQuarterSqlpart1.toString () + conditionSql.toString () + planQuarterSqlpart2.toString () );
            rsMap.put ( "areaMapList_todo", areaMapList );
            rsMap.put ( "planMonthMapList_todo", planMonthMapList );


            if (!area.equals ( "" )) {
                conditionSql.append ( " AND tt.id ='" ).append ( area ).append ( "' " );
            }
            if (StringUtil.isNotEmpty ( planYear ) && StringUtil.isNotEmpty ( planMonth )) {
                conditionSql.append ( " AND YEAR(ip.ip_plan_date) ='" ).append ( planYear ).append ( "' " );
                conditionSql.append ( " AND MONTH(ip.ip_plan_date) ='" ).append ( planMonth ).append ( "' " );
            }
            if (!esSn.equals ( "" )) {
                conditionSql.append ( " AND es.sn ='" ).append ( esSn ).append ( "' " );
            }
            if (!cmId.equals ( "" )) {
                conditionSql.append ( " AND cm.id ='" ).append ( cmId ).append ( "' " );
            }
            List<Map<String, Object>> egIpMapList_todo = new ArrayList<Map<String, Object>> ();
            List<Map<String, Object>> groupMap_todo = super.findForJdbc ( groupSqlpart1.toString () + conditionSql.toString () + groupSqlpart2.toString () );
            List<Map<String, Object>> detailMap_todo = super.findForJdbc ( detailSql.toString () + conditionSql.toString () );
            //合并
            for (Map<String, Object> cmM : groupMap_todo) {
                if (null != cmM) {
                    Map<String, Object> m = new HashMap<String, Object> ();
                    m.put ( "cmM", cmM );
                    List<Map<String, Object>> dtMapList = new ArrayList<Map<String, Object>> ();
                    for (Map<String, Object> dtM : detailMap_todo) {
                        if (null != dtM.get ( "cmId" ) && dtM.get ( "cmId" ).equals ( cmM.get ( "cmId" ) )) {
                            dtMapList.add ( dtM );
                        }
                        m.put ( "dtMapList", dtMapList );//是不是null 都put进去，防止页面取值出现问题
                    }
                    egIpMapList_todo.add ( m );
                }
            }

            rsMap.put ( "egIpMapList_todo", egIpMapList_todo );
        }
        /**------ 待处理---end--*/
        /**------ 服务中-----*/
        if (type == 2) {
            conditionSql = new StringBuffer ();
            conditionSql.append ( " WHERE " );
            conditionSql.append ( " ip.state IN (" );
            conditionSql.append ( "'" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED ).append ( "'," );
            conditionSql.append ( "'" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT ).append ( "'" );
            conditionSql.append ( ") " );
            conditionSql.append(" AND ip.engineer = '").append(engineerId).append("' ");//只查询指派到自己的
//            if (null != idsList && idsList.size () > 0) {
//                conditionSql.append ( " AND ip.id IN (" );
//                for (int i = 0; i < idsList.size (); i++) {
//                    if (i == idsList.size () - 1) {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'" );
//                    } else {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'," );
//                    }
//                }
//                conditionSql.append ( " ) " );
//            } else {
//                conditionSql.append ( " AND 1 != 1" );
//            }

            areaMapList = super.findForJdbc ( citySqlpart1.toString () + conditionSql.toString () + citySqlpart2.toString () );
            planMonthMapList = super.findForJdbc ( planQuarterSqlpart1.toString () + conditionSql.toString () + planQuarterSqlpart2.toString () );
            rsMap.put ( "areaMapList_in_service", areaMapList );
            rsMap.put ( "planMonthMapList_in_service", planMonthMapList );

            if (!area.equals ( "" )) {
                conditionSql.append ( " AND tt.id ='" ).append ( area ).append ( "' " );
            }
            if (StringUtil.isNotEmpty ( planYear ) && StringUtil.isNotEmpty ( planMonth )) {
                conditionSql.append ( " AND YEAR(ip.ip_plan_date) ='" ).append ( planYear ).append ( "' " );
                conditionSql.append ( " AND MONTH(ip.ip_plan_date) ='" ).append ( planMonth ).append ( "' " );
            }
            if (!esSn.equals ( "" )) {
                conditionSql.append ( " AND es.sn ='" ).append ( esSn ).append ( "' " );
            }
            if (!cmId.equals ( "" )) {
                conditionSql.append ( " AND cm.id ='" ).append ( cmId ).append ( "' " );
            }
            List<Map<String, Object>> egIpMapList_in_service = new ArrayList<Map<String, Object>> ();
            List<Map<String, Object>> groupMap_in_services = super.findForJdbc ( groupSqlpart1.toString () + conditionSql.toString () + groupSqlpart2.toString () );
            List<Map<String, Object>> detailMap_in_services = super.findForJdbc ( detailSql.toString () + conditionSql.toString () );
            //合并
            for (Map<String, Object> cmM : groupMap_in_services) {
                if (null != cmM) {
                    Map<String, Object> m = new HashMap<String, Object> ();
                    m.put ( "cmM", cmM );
                    List<Map<String, Object>> dtMapList = new ArrayList<Map<String, Object>> ();
                    for (Map<String, Object> dtM : detailMap_in_services) {
                        if (null != dtM.get ( "cmId" ) && dtM.get ( "cmId" ).equals ( cmM.get ( "cmId" ) )) {
                            dtMapList.add ( dtM );
                        }
                        m.put ( "dtMapList", dtMapList );//是不是null 都put进去，防止页面取值出现问题
                    }
                    egIpMapList_in_service.add ( m );
                }
            }

            rsMap.put ( "egIpMapList_in_service", egIpMapList_in_service );
        }
        /**------ 服务中---end--*/
        /**------ 已完成-----*/
        if (type == 3) {
//            StringBuffer sql = new StringBuffer ();//3个月内 。这个比对的时间只好拿 巡检记录的时间
//            sql.append ( " SELECT " );
//            sql.append ( " 	DISTINCT pr.bus_id AS busId " );
//            sql.append ( " FROM " );
//            sql.append ( " 	zy_plan_record pr " );
//            sql.append ( " WHERE pr.create_by = '" ).append ( user.getUserName () ).append ( "' " );
//            sql.append ( " AND pr.plan_state = '" ).append ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE ).append ( "' " );
//            sql.append ( " AND DATE_SUB(CURDATE(), INTERVAL 3 MONTH) <= pr.create_date " );
//            List<Map<String, Object>> idsMapList = super.findForJdbc ( sql.toString () );
//            if (null != idsMapList && idsMapList.size () > 0) {
//                for (int i = 0; i < idsMapList.size (); i++) {
//                    if (null != idsMapList.get ( i )) {
//                        idsList.add ( idsMapList.get ( i ).get ( "busId" ).toString () );
//                    }
//                }
//            }
            conditionSql = new StringBuffer ();
            conditionSql.append ( " WHERE " );
            conditionSql.append ( " ip.state = '" ).append ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE ).append ( "' " );
            conditionSql.append(" and DATE_SUB(CURDATE(), INTERVAL 3 MONTH) <= ip.ip_plan_date ");//查询三个月内的
            conditionSql.append(" AND ip.engineer = '").append(engineerId).append("' ");//只查询指派到自己的
//            if (null != idsList && idsList.size () > 0) {
//                conditionSql.append ( " AND ip.id IN (" );
//                for (int i = 0; i < idsList.size (); i++) {
//                    if (i == idsList.size () - 1) {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'" );
//                    } else {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'," );
//                    }
//                }
//                conditionSql.append ( " ) " );
//            } else {
//                conditionSql.append ( " AND 1 != 1" );
//            }

            areaMapList = super.findForJdbc ( citySqlpart1.toString () + conditionSql.toString () + citySqlpart2.toString () );
            planMonthMapList = super.findForJdbc ( planQuarterSqlpart1.toString () + conditionSql.toString () + planQuarterSqlpart2.toString () );
            rsMap.put ( "areaMapList_already_done", areaMapList );
            rsMap.put ( "planMonthMapList_already_done", planMonthMapList );

            if (!area.equals ( "" )) {
                conditionSql.append ( " AND tt.id ='" ).append ( area ).append ( "' " );
            }
            if (StringUtil.isNotEmpty ( planYear ) && StringUtil.isNotEmpty ( planMonth )) {
                conditionSql.append ( " AND YEAR(ip.ip_plan_date) ='" ).append ( planYear ).append ( "' " );
                conditionSql.append ( " AND MONTH(ip.ip_plan_date) ='" ).append ( planMonth ).append ( "' " );
            }
            if (!esSn.equals ( "" )) {
                conditionSql.append ( " AND es.sn ='" ).append ( esSn ).append ( "' " );
            }
            if (!cmId.equals ( "" )) {
                conditionSql.append ( " AND cm.id ='" ).append ( cmId ).append ( "' " );
            }
            List<Map<String, Object>> egIpMapList_already_done = new ArrayList<Map<String, Object>> ();
            List<Map<String, Object>> groupMap_already_done = super.findForJdbc ( groupSqlpart1.toString () + conditionSql.toString () + groupSqlpart2.toString () );
            List<Map<String, Object>> detailMap_already_done = super.findForJdbc ( detailSql.toString () + conditionSql.toString () );
            //合并
            for (Map<String, Object> cmM : groupMap_already_done) {
                if (null != cmM) {
                    Map<String, Object> m = new HashMap<String, Object> ();
                    m.put ( "cmM", cmM );
                    List<Map<String, Object>> dtMapList = new ArrayList<Map<String, Object>> ();
                    for (Map<String, Object> dtM : detailMap_already_done) {
                        if (null != dtM.get ( "cmId" ) && dtM.get ( "cmId" ).equals ( cmM.get ( "cmId" ) )) {
                            dtMapList.add ( dtM );
                        }
                        m.put ( "dtMapList", dtMapList );//是不是null 都put进去，防止页面取值出现问题
                    }
                    egIpMapList_already_done.add ( m );
                }
            }

            rsMap.put ( "egIpMapList_already_done", egIpMapList_already_done );
        }
        /**------ 已完成---end--*/
        /**------ 已拒绝-----*/
        if (type == 4) {
            conditionSql = new StringBuffer ();
            conditionSql.append ( " WHERE " );
            conditionSql.append ( " ip.state = '" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED ).append ( "' " );
            conditionSql.append(" AND ip.engineer = '").append(engineerId).append("' ");//只查询指派到自己的
//            if (null != idsList && idsList.size () > 0) {
//                conditionSql.append ( " AND ip.id IN (" );
//                for (int i = 0; i < idsList.size (); i++) {
//                    if (i == idsList.size () - 1) {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'" );
//                    } else {
//                        conditionSql.append ( "'" + idsList.get ( i ) + "'," );
//                    }
//                }
//                conditionSql.append ( " ) " );
//            } else {
//                conditionSql.append ( " AND 1 != 1" );
//            }

            areaMapList = super.findForJdbc ( citySqlpart1.toString () + conditionSql.toString () + citySqlpart2.toString () );
            planMonthMapList = super.findForJdbc ( planQuarterSqlpart1.toString () + conditionSql.toString () + planQuarterSqlpart2.toString () );
            rsMap.put ( "areaMapList_already_refuse", areaMapList );
            rsMap.put ( "planMonthMapList_already_refuse", planMonthMapList );

            if (!area.equals ( "" )) {
                conditionSql.append ( " AND tt.id ='" ).append ( area ).append ( "' " );
            }
            if (StringUtil.isNotEmpty ( planYear ) && StringUtil.isNotEmpty ( planMonth )) {
                conditionSql.append ( " AND YEAR(ip.ip_plan_date) ='" ).append ( planYear ).append ( "' " );
                conditionSql.append ( " AND MONTH(ip.ip_plan_date) ='" ).append ( planMonth ).append ( "' " );
            }
            if (!esSn.equals ( "" )) {
                conditionSql.append ( " AND es.sn ='" ).append ( esSn ).append ( "' " );
            }
            if (!cmId.equals ( "" )) {
                conditionSql.append ( " AND cm.id ='" ).append ( cmId ).append ( "' " );
            }
            List<Map<String, Object>> egIpMapList_already_refuse = new ArrayList<Map<String, Object>> ();
            List<Map<String, Object>> groupMap_already_refuse = super.findForJdbc ( groupSqlpart1.toString () + conditionSql.toString () + groupSqlpart2.toString () );
            List<Map<String, Object>> detailMap_already_refuse = super.findForJdbc ( detailSql.toString () + conditionSql.toString () );
            //合并
            for (Map<String, Object> cmM : groupMap_already_refuse) {
                if (null != cmM) {
                    Map<String, Object> m = new HashMap<String, Object> ();
                    m.put ( "cmM", cmM );
                    List<Map<String, Object>> dtMapList = new ArrayList<Map<String, Object>> ();
                    for (Map<String, Object> dtM : detailMap_already_refuse) {
                        if (null != dtM.get ( "cmId" ) && dtM.get ( "cmId" ).equals ( cmM.get ( "cmId" ) )) {
                            dtMapList.add ( dtM );
                        }
                        m.put ( "dtMapList", dtMapList );//是不是null 都put进去，防止页面取值出现问题
                    }
                    egIpMapList_already_refuse.add ( m );
                }
            }

            rsMap.put ( "egIpMapList_already_refuse", egIpMapList_already_refuse );
        }
        /**------ 已拒绝---end--*/

        return rsMap;
    }


    @Override
    public Map<String, Object> queryIpDetailOfTP(String ipId) {
        Map<String, Object> rsMap = new HashMap<String, Object> ();
        StringBuffer sql = new StringBuffer ();
        //巡检详情
        sql.append ( " SELECT " );
        sql.append ( " 	es.sn, ip.plan_id AS planId, MONTH(ip.ip_plan_date) AS ipMonth,tp_1.typename AS lightPathVal,ip.remarks," );
        sql.append ( "	IFNULL(DATE_FORMAT(ip.end_time,'%Y-%m-%d'),'无') AS endTime," );
        sql.append ( "	IFNULL(ip.company_had_area_eg,'0') AS companyHadAreaEgVal, IFNULL(DATE_FORMAT(ip.engineer_order_time,'%Y-%m-%d'),'无') AS engineerOrderTime, " );
        sql.append ( " 	rm.room_num AS roomNum, et.type_desc AS esTypeDesc, es.laser_reconstruction AS laser, " );
        sql.append ( "	CASE es.laser_reconstruction WHEN '1' THEN '是' ELSE '否' END AS laserVal, IFNULL(DATE_FORMAT(es.last_year_inspection_date,'%Y-%m-%d'),'无') AS lastYearInspectionDate, " );
        sql.append ( " 	IF(TIMESTAMPDIFF(DAY,NOW(),es.repair_end_date) < 0 ,'保外','保内') AS inReparirDateVal, " );
        sql.append ( "	CASE tp_2.typecode WHEN '" ).append ( StaticValue.DIC_SERVER_STATE_1001 ).append ( "' THEN '1' ELSE '0' END AS inServer, " );
        sql.append ( "	CASE ip.state WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY ).append ( "' THEN '1' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED ).append ( "' THEN '2' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_REFUSED ).append ( "' THEN '3' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_ASSIGNED ).append ( "' THEN '4' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_REFUSED ).append ( "' THEN '5' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED ).append ( "' THEN '6' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED ).append ( "' THEN '7' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT ).append ( "' THEN '8' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE ).append ( "' THEN '9' END AS ipState, " );
        sql.append ( " 	tp_2.typename AS serverStateVal, cm.id AS cmId, cm.`name` AS cmName, cm.address, tt.territoryname, ptt.territoryname AS pTerritoryname, IFNULL(dp.departname,'无') AS departname, " );
        sql.append ( "	ct.`name` AS tecDirectorName, ct.cellphone1 AS tecDirectorCellphone, ct_1.`name` AS ipCtName, ct_1.cellphone1 AS ipCtCellphone " );
        sql.append ( " FROM " );
        sql.append ( " 	zy_inspection_plan ip " );
//        sql.append(" LEFT JOIN t_s_typegroup tg ON tg.typegroupcode = '").append(StaticValue.DIC_PLAN_INSPECTION_QUARTER).append("' ");
//        sql.append(" LEFT JOIN t_s_type tp ON tp.typecode = ip.plan_quarter AND tg.ID = tp.typegroupid ");
        sql.append ( " LEFT JOIN t_s_typegroup tg_1 ON tg_1.typegroupcode = '" ).append ( StaticValue.DIC_LIGHT_PATH ).append ( "' " );
        sql.append ( " LEFT JOIN t_s_type tp_1 ON tp_1.typecode = ip.light_path AND tg_1.ID = tp_1.typegroupid " );
        sql.append ( " LEFT JOIN zy_equipment_spare es ON es.id = ip.equipment_spare_id " );
        sql.append ( " LEFT JOIN t_s_typegroup tg_2 ON tg_2.typegroupcode = '" ).append ( StaticValue.DIC_SERVER_STATE ).append ( "' " );
        sql.append ( " LEFT JOIN t_s_type tp_2 ON tp_2.typecode = es.server_state AND tg_2.ID = tp_2.typegroupid " );
        sql.append ( " LEFT JOIN zy_equipment_type et ON et.id = es.type " );
        sql.append ( " LEFT JOIN zy_cinema cm ON cm.id = es.belong_cinema_id " );
        sql.append ( " LEFT JOIN t_s_territory tt ON tt.ID = cm.city " );
        sql.append ( " LEFT JOIN t_s_territory ptt ON ptt.ID = tt.territoryparentid " );
        sql.append ( " LEFT JOIN t_s_depart dp ON dp.id = cm.belong_org " );
        sql.append ( " LEFT JOIN zy_room rm ON rm.id = es.house " );
        sql.append ( " LEFT JOIN zy_contacts ct ON ct.belong_cinema = cm.id " );
        sql.append ( " 	AND ct.state = '" ).append ( StaticValue.DIC_ENGINEER_STATE_ONJOB ).append ( "' " );
        sql.append ( " 	AND ct.is_delete = 0 " );
        sql.append ( " 	AND ct.type = '" ).append ( StaticValue.DIC_CONTACT_TYPE_CINEMA_CONTACT ).append ( "' " );
        sql.append ( " 	AND ct.position = '" ).append ( StaticValue.DIC_CONTACT_POSITION_C_TECHNICAL_DIRECTOR ).append ( "' " );
        sql.append ( " LEFT JOIN zy_contacts ct_1 on ct_1.belong_cinema = cm.id " );
        sql.append ( " 	AND ct_1.state = '" ).append ( StaticValue.DIC_ENGINEER_STATE_ONJOB ).append ( "' " );
        sql.append ( " 	AND ct_1.is_delete = 0 " );
        sql.append ( " 	AND ct_1.type = '" ).append ( StaticValue.DIC_CONTACT_TYPE_CINEMA_CONTACT ).append ( "' " );
        sql.append ( " 	AND ct_1.con_business LIKE '%" ).append ( StaticValue.DIC_BUS_SCOPE_INSPECTION ).append ( "%' " );
        sql.append ( " WHERE " );
        sql.append ( " 	ip.id = '" ).append ( ipId ).append ( "' " );
        Map<String, Object> ipDetailMap = super.findForJdbc ( sql.toString () ).get ( 0 );//这里因为 影院的联系人 和影院技术主管可能存在多个人。所以用 get 0
        rsMap.put ( "ipDetail", ipDetailMap );

        sql = new StringBuffer ();
        sql.append ( " SELECT " );
        sql.append ( " 	pr.create_name AS createName, " );
        sql.append ( " 	pr.remark " );
        sql.append ( " FROM " );
        sql.append ( " 	zy_plan_record pr " );
        sql.append ( " WHERE " );
        sql.append ( " 	pr.bus_id = '" ).append ( ipId ).append ( "' " );
        sql.append ( " ORDER BY " );
        sql.append ( " 	pr.create_date DESC " );
        sql.append ( " LIMIT 1 " );
        rsMap.put ( "ipLastRecord", super.findOneForJdbc ( sql.toString () ) );//巡检计划记录，配合巡检状态显示，不同于下面的巡检查询

        boolean flag = true;
        if (null != ipDetailMap && StringUtil.isNotEmpty ( ipDetailMap.get ( "tpRefuse" ) )) {
            if (ipDetailMap.get ( "tpRefuse" ).toString ().equals ( "1" )) {//如果是第三方拒绝则不用查询数据了
                flag = false;
            }
        }
        if (flag) {
            //巡检进度
            sql = new StringBuffer ();
            sql.append ( " SELECT " );
            sql.append ( " 	pr.remark, DATE_FORMAT(pr.create_date,'%Y-%m-%d %H:%i:%s') AS createDate, " );
            sql.append ( "	CASE pr.plan_state WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE ).append ( "' THEN '1' ELSE '0' END AS isDone " );
            sql.append ( " FROM " );
            sql.append ( " 	zy_plan_record pr " );
            sql.append ( " WHERE " );
            sql.append ( " 	bus_id = '" ).append ( ipId ).append ( "' " );
            sql.append ( " ORDER BY pr.create_date " );
            rsMap.put ( "ipRecord", super.findForJdbc ( sql.toString () ) );
            ZyInspectionReportEntity zyIr = super.findUniqueByProperty ( ZyInspectionReportEntity.class, "inspectionPlanId", ipId );
            if (null != zyIr) {
                //巡检报告
                sql = new StringBuffer ();
                sql.append ( " SELECT " );
                sql.append ( "	cm.`name` AS cmName, ip.plan_id AS planId," );
                sql.append ( " 	IFNULL(ir.house_name, '无') AS houseName, IFNULL(ir.cm_actual_name, '无') AS cmActualName,  " );
                sql.append ( " 	IFNULL(ir.cm_actual_addr, '无') AS cmActualAddr, IFNULL(ir.inp_con_user, '无') AS inpConUser,  " );
                sql.append ( " 	IFNULL(ir.inp_con_user_tel, '无') AS inpConUserTel, IFNULL(ir.yt_score_rm, '无') AS ytScoreRm,  " );
                sql.append ( " 	IFNULL(ir.yt_rm_temperature, '无') AS ytRmTemperature, IFNULL(ir.yt_rm_humidity, '无') AS ytRmHumidity,  " );
                sql.append ( " 	IFNULL(ir.yt_score_screen, '无') AS ytScoreScreen, IFNULL(ir.yt_score_ce, '无') AS ytScoreCe,  " );
                sql.append ( " 	IFNULL(ir.yt_problem, '无') AS ytProblem, IFNULL(ir.yt_is_secl_is_Illegal, '无') AS ytIsSeclIsIllegal, " );
                sql.append ( " 	IFNULL(et.type_desc, '无') AS tmsBrandVal, " );
                sql.append ( " 	CASE ir.tms_lan_conn_is_nomal WHEN '1' THEN '是' ELSE '否' END AS tmsLanConnIsNomalVal, " );
                sql.append ( " 	CASE ir.tms_dcp_trans_is_normal WHEN '1' THEN '是' ELSE '否' END AS tmsDcpTransIsNormalVal, " );
                sql.append ( " 	CASE ir.tms_pe_control_is_normal WHEN '1' THEN '是' ELSE '否' END AS tmsPeControlIsNormalVal, " );
                sql.append ( " 	CASE ir.tms_sl_schedule_is_normal WHEN '1' THEN '是' ELSE '否' END AS tmsSlScheduleIsNormalVal, " );
                sql.append ( " 	ir.server_brand_other AS serverBrandOther, IFNULL(et1.type_desc, '无') AS serverBrandVal, IFNULL(ir.server_model, '无') AS serverModel,  " );
                sql.append ( " 	IFNULL(ir.qj_score_overall, '无') AS qjScoreOverall, IFNULL(ir.qj_score_dust_filter, '无') AS qjScoreDustFilter,  " );
                sql.append ( " 	IFNULL(ir.qj_score_aire_inlet, '无') AS qjScoreAireInlet, IFNULL(ir.qj_score_ele_box, '无') AS qjScoreEleBox,  " );
                sql.append ( " 	IFNULL(ir.gx_score_cam_lens, '无') AS gxScoreCamLens, IFNULL(ir.gx_cam_lens, '无') AS gxCamLens,  " );
                sql.append ( " 	IFNULL(ir.gx_score_reflective_lens, '无') AS gxScoreReflectiveLens, IFNULL(ir.gx_score_light_path, '无') AS gxScoreLightPath,  " );
                sql.append ( " 	IFNULL(tp.typename, '无') AS gxLightPathVal," );
                sql.append ( "	CONCAT(" );
                sql.append ( "		IF (FIND_IN_SET(1, gx_light_path_charges_mp) > 0 ,'光管翻新,', '')," );
                sql.append ( "		IF (FIND_IN_SET(2, gx_light_path_charges_mp) > 0 ,'引擎翻新,', '')," );
                sql.append ( "		IF (FIND_IN_SET(3, gx_light_path_charges_mp) > 0 ,'深度清洁', '')" );
                sql.append ( "	) AS gxLightPathChargesMpVal, " );
                sql.append ( " 	IFNULL(ir.lq_score_vent_speed, '无') AS lqScoreVentSpeed, IFNULL(ir.lq_score_coolant, '无') AS lqScoreCoolant,  " );
                sql.append ( " 	IFNULL(ir.lq_score_running_state, '无') AS lqScoreRunningState, IFNULL(ir.lq_is_leak_liquid, '无') AS lqIsLeakLiquid, " );
                sql.append ( " 	IFNULL(ir.lq_is_insulation, '无') AS lqIsInsulation, IFNULL(ir.gy_dryer_cw_is_normal, '无') AS gyDryerCwIsNormal, " );
                sql.append ( " 	IFNULL(ir.gy_laser_is_normal, '无') AS gyLaserIsNormal, IFNULL(ir.xd_score_xn,'无') AS xdScoreXn,  " );
                sql.append ( " 	IFNULL(ir.xd_brand,'无') AS xdBrand, IFNULL(ir.xd_score_joints,'无') AS xdScoreJoints,  " );
                sql.append ( " 	IFNULL(ir.xl_score_ac,'无') AS xlScoreAc, IFNULL(ir.xl_score_voltage,'无') AS xlScoreVoltage,  " );
                sql.append ( " 	IFNULL(ir.yx_score_focus,'无') AS yxScoreFocus, IFNULL(ir.yx_score_frame,'无') AS yxScoreFrame,  " );
                sql.append ( " 	IFNULL(ir.yx_light_c,'无') AS yxLightC, IFNULL(ir.yx_light_left,'无') AS yxLightLeft,  " );
                sql.append ( " 	IFNULL(ir.yx_light_center,'无') AS yxLightCenter, IFNULL(ir.yx_light_right,'无') AS yxLightRight,  " );
                sql.append ( " 	IFNULL(ir.yx_score_3d,'无') AS yxScore3d,  " );
                sql.append ( " 	CASE ir.yx_3d_type WHEN '1' THEN '双机偏振' WHEN '2' THEN '主动' WHEN '3' THEN 'RealD' WHEN '4' THEN 'Dolby' ELSE '无' END  AS yx3dTypeVal, " );
                sql.append ( " 	IFNULL(ir.yx_3d_light, '无') AS yx3dLight, " );
                sql.append ( " 	CASE ir.fwq_hd_space_speed_mp WHEN '1' THEN '维修' WHEN '2' THEN '清理' WHEN '3' THEN '合格' ELSE '无' END AS fwqHdSpaceSpeedMpVal, " );
                sql.append ( " 	CASE ir.fwq_time_calibration_mp WHEN '1' THEN '校准' WHEN '2' THEN '正确' ELSE '无' END AS fwqTimeCalibrationMpVal, " );
                sql.append ( " 	IFNULL(ir.score_projector_mb, '无') AS scoreProjectorMb,  " );
                sql.append ( " 	CASE ir.projector_mb_mp WHEN 'on' THEN '暂无' ELSE '有' END AS projectorMbMpVal, " );
                sql.append ( " 	IFNULL(ir.before_score, '无') AS beforeScore, IFNULL(ir.after_score, '无') AS afterScore,  " );
                sql.append ( " 	IFNULL(ir.remark, '无') AS remark, IFNULL(ir.training_num, '无') AS trainingNum,  " );
                sql.append ( " 	IFNULL(ir.training_score, '无') AS trainingScore, IFNULL(ir.comprehensive_evaluation, '无') AS comprehensiveEvaluation " );
                sql.append ( " FROM  " );
                sql.append ( " 	zy_inspection_plan ip  " );
                sql.append ( " LEFT JOIN zy_equipment_spare es on es.id = ip.equipment_spare_id " );
                sql.append ( " LEFT JOIN zy_cinema cm on cm.id = es.belong_cinema_id " );
                sql.append ( " LEFT JOIN zy_inspection_report ir ON ir.inspection_plan_id = ip.id " );
                sql.append ( " LEFT JOIN zy_equipment_type et on et.id = ir.tms_brand " );
                sql.append ( " LEFT JOIN zy_equipment_type et1 on et1.id = ir.server_brand " );
                sql.append ( " LEFT JOIN t_s_typegroup tg on tg.typegroupcode = '" ).append ( StaticValue.DIC_LIGHT_PATH ).append ( "' " );
                sql.append ( " LEFT JOIN t_s_type tp on tp.typecode = ir.gx_light_path AND tg.id = tp.typegroupid " );
                sql.append ( " WHERE " );
                sql.append ( " 	ip.id = '" ).append ( ipId ).append ( "' " );
                rsMap.put ( "ipReport", super.findOneForJdbc ( sql.toString () ) );

                sql = new StringBuffer ();
                sql.append ( " SELECT " );
                sql.append ( " 	ra.file_log_id " );
                sql.append ( " FROM " );
                sql.append ( " 	zy_report_attachment ra " );
                sql.append ( " LEFT JOIN zy_inspection_report ir on ir.id = ra.report_id " );
                sql.append ( " left JOIN zy_inspection_plan ip on ip.id = ir.inspection_plan_id " );
                sql.append ( " WHERE " );
                sql.append ( " 	ip.id = '" ).append ( ipId ).append ( "' " );
                sql.append ( " AND ra.type = ? " );

                rsMap.put ( "irCompletion", super.findForJdbc ( sql.toString (), StaticValue.DIC_REPORT_ATTACH_TYPE_COMPLETION_IMAGE ) );//巡检报告 完工单附件
                rsMap.put ( "irInspection", super.findForJdbc ( sql.toString (), StaticValue.DIC_REPORT_ATTACH_TYPE_INSPECTION_IMAGE ) );//巡检报告 巡检图片附件
            }
            //巡检评价
            sql = new StringBuffer ();
            sql.append ( " SELECT " );
            sql.append ( " 	cie.id cieId, cm.`name` AS cmName, DATE_FORMAT(cie.create_date,'%Y-%m-%d %H:%i:%s') AS cieUpdateDate, cie.opinion, " );
            sql.append ( " 	cie.last_evaluate AS lastEvaluate, cie.service_evaluate AS serviceEvaluate, cie.talk_evaluate AS talkEvaluate, " );
            sql.append ( " 	cie.effect_evaluate AS effectEvaluate ,cie.train_evaluate AS trainEvaluate, cie.effect_evaluate AS effectEvaluate, cie.skill_evaluate AS skillEvaluate " );
            sql.append ( " FROM " );
            sql.append ( " 	cbs_inspection_evaluate cie " );
            sql.append ( " LEFT JOIN zy_inspection_plan ip on ip.id = cie.inspection_id " );
            sql.append ( " LEFT JOIN zy_equipment_spare es on es.id = ip.equipment_spare_id " );
            sql.append ( " LEFT JOIN zy_cinema cm on cm.id = es.belong_cinema_id " );
            sql.append ( " WHERE " );
            sql.append ( "	cie.evaluate_state <> '" ).append ( StaticValue.DIC_EVALUATE_STATE_0 ).append ( "' " );
            sql.append ( " 	AND cie.inspection_id = '" ).append ( ipId ).append ( "' " );
            rsMap.put ( "ipEvaluate", super.findOneForJdbc ( sql.toString () ) );
        }
        return rsMap;
    }


    @Override
    public Map<String, Object> queryIpDetailOfAeg(String ipId) {
        Map<String, Object> rsMap = new HashMap<String, Object> ();
        StringBuffer sql = new StringBuffer ();
        //巡检详情
        sql.append ( " SELECT " );
        sql.append ( " 	es.sn, ip.plan_id AS planId, MONTH(ip.ip_plan_date) AS ipMonth,tp_1.typename AS lightPathVal,ip.remarks," );
        sql.append ( "	IFNULL(DATE_FORMAT(ip.end_time,'%Y-%m-%d'),'无') AS endTime," );
        sql.append ( "	IFNULL(ip.company_had_area_eg,'0') AS companyHadAreaEgVal, IFNULL(DATE_FORMAT(ip.engineer_order_time,'%Y-%m-%d'),'无') AS engineerOrderTime, " );
        sql.append ( " 	rm.room_num AS roomNum, et.type_desc AS esTypeDesc, es.laser_reconstruction AS laser, " );
        sql.append ( "	CASE es.laser_reconstruction WHEN '1' THEN '是' ELSE '否' END AS laserVal, IFNULL(DATE_FORMAT(es.last_year_inspection_date,'%Y-%m-%d'),'无') AS lastYearInspectionDate, " );
        sql.append ( " 	IF(TIMESTAMPDIFF(DAY,NOW(),es.repair_end_date) < 0 ,'保外','保内') AS inReparirDateVal, " );
        sql.append ( "	CASE tp_2.typecode WHEN '" ).append ( StaticValue.DIC_SERVER_STATE_1001 ).append ( "' THEN '1' ELSE '0' END AS inServer, " );
        sql.append ( "	CASE ip.state WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY ).append ( "' THEN '1' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED ).append ( "' THEN '2' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_REFUSED ).append ( "' THEN '3' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_ASSIGNED ).append ( "' THEN '4' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_REFUSED ).append ( "' THEN '5' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED ).append ( "' THEN '6' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED ).append ( "' THEN '7' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT ).append ( "' THEN '8' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE ).append ( "' THEN '9' END AS ipState, " );
        sql.append ( " 	tp_2.typename AS serverStateVal, cm.id AS cmId, cm.`name` AS cmName, cm.address, tt.territoryname, ptt.territoryname AS pTerritoryname, IFNULL(dp.departname,'无') AS departname, " );
        sql.append ( "	ct.`name` AS tecDirectorName, ct.cellphone1 AS tecDirectorCellphone, ct_1.`name` AS ipCtName, ct_1.cellphone1 AS ipCtCellphone " );
        sql.append ( " FROM " );
        sql.append ( " 	zy_inspection_plan ip " );
//        sql.append(" LEFT JOIN t_s_typegroup tg ON tg.typegroupcode = '").append(StaticValue.DIC_PLAN_INSPECTION_QUARTER).append("' ");
//        sql.append(" LEFT JOIN t_s_type tp ON tp.typecode = ip.plan_quarter AND tg.ID = tp.typegroupid ");
        sql.append ( " LEFT JOIN t_s_typegroup tg_1 ON tg_1.typegroupcode = '" ).append ( StaticValue.DIC_LIGHT_PATH ).append ( "' " );
        sql.append ( " LEFT JOIN t_s_type tp_1 ON tp_1.typecode = ip.light_path AND tg_1.ID = tp_1.typegroupid " );
        sql.append ( " LEFT JOIN zy_equipment_spare es ON es.id = ip.equipment_spare_id " );
        sql.append ( " LEFT JOIN t_s_typegroup tg_2 ON tg_2.typegroupcode = '" ).append ( StaticValue.DIC_SERVER_STATE ).append ( "' " );
        sql.append ( " LEFT JOIN t_s_type tp_2 ON tp_2.typecode = es.server_state AND tg_2.ID = tp_2.typegroupid " );
        sql.append ( " LEFT JOIN zy_equipment_type et ON et.id = es.type " );
        sql.append ( " LEFT JOIN zy_cinema cm ON cm.id = es.belong_cinema_id " );
        sql.append ( " LEFT JOIN t_s_territory tt ON tt.ID = cm.city " );
        sql.append ( " LEFT JOIN t_s_territory ptt ON ptt.ID = tt.territoryparentid " );
        sql.append ( " LEFT JOIN t_s_depart dp ON dp.id = cm.belong_org " );
        sql.append ( " LEFT JOIN zy_room rm ON rm.id = es.house " );
        sql.append ( " LEFT JOIN zy_contacts ct ON ct.belong_cinema = cm.id " );
        sql.append ( " 	AND ct.state = '" ).append ( StaticValue.DIC_ENGINEER_STATE_ONJOB ).append ( "' " );
        sql.append ( " 	AND ct.is_delete = 0 " );
        sql.append ( " 	AND ct.type = '" ).append ( StaticValue.DIC_CONTACT_TYPE_CINEMA_CONTACT ).append ( "' " );
        sql.append ( " 	AND ct.position = '" ).append ( StaticValue.DIC_CONTACT_POSITION_C_TECHNICAL_DIRECTOR ).append ( "' " );
        sql.append ( " LEFT JOIN zy_contacts ct_1 on ct_1.belong_cinema = cm.id " );
        sql.append ( " 	AND ct_1.state = '" ).append ( StaticValue.DIC_ENGINEER_STATE_ONJOB ).append ( "' " );
        sql.append ( " 	AND ct_1.is_delete = 0 " );
        sql.append ( " 	AND ct_1.type = '" ).append ( StaticValue.DIC_CONTACT_TYPE_CINEMA_CONTACT ).append ( "' " );
        sql.append ( " 	AND ct_1.con_business LIKE '%" ).append ( StaticValue.DIC_BUS_SCOPE_INSPECTION ).append ( "%' " );
        sql.append ( " WHERE " );
        sql.append ( " 	ip.id = '" ).append ( ipId ).append ( "' " );
        Map<String, Object> ipDetailMap = super.findForJdbc ( sql.toString () ).get ( 0 );//这里因为 影院的联系人 和影院技术主管可能存在多个人。所以用 get 0
        rsMap.put ( "ipDetail", ipDetailMap );

        sql = new StringBuffer ();
        sql.append ( " SELECT " );
        sql.append ( " 	pr.create_name AS createName, " );
        sql.append ( " 	pr.remark " );
        sql.append ( " FROM " );
        sql.append ( " 	zy_plan_record pr " );
        sql.append ( " WHERE " );
        sql.append ( " 	pr.bus_id = '" ).append ( ipId ).append ( "' " );
        sql.append ( " ORDER BY " );
        sql.append ( " 	pr.create_date DESC " );
        sql.append ( " LIMIT 1 " );
        rsMap.put ( "ipLastRecord", super.findOneForJdbc ( sql.toString () ) );//巡检计划记录，配合巡检状态显示，不同于下面的巡检查询

        boolean flag = true;
        if (null != ipDetailMap && StringUtil.isNotEmpty ( ipDetailMap.get ( "tpRefuse" ) )) {
            if (ipDetailMap.get ( "tpRefuse" ).toString ().equals ( "1" )) {//如果是第三方拒绝则不用查询数据了
                flag = false;
            }
        }
        if (flag) {
            //巡检进度
            sql = new StringBuffer ();
            sql.append ( " SELECT " );
            sql.append ( " 	pr.remark, DATE_FORMAT(pr.create_date,'%Y-%m-%d %H:%i:%s') AS createDate, " );
            sql.append ( "	CASE pr.plan_state WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE ).append ( "' THEN '1' ELSE '0' END AS isDone " );
            sql.append ( " FROM " );
            sql.append ( " 	zy_plan_record pr " );
            sql.append ( " WHERE " );
            sql.append ( " 	bus_id = '" ).append ( ipId ).append ( "' " );
            sql.append ( " ORDER BY pr.create_date " );
            rsMap.put ( "ipRecord", super.findForJdbc ( sql.toString () ) );
            ZyInspectionReportEntity zyIr = super.findUniqueByProperty ( ZyInspectionReportEntity.class, "inspectionPlanId", ipId );
            if (null != zyIr) {
                //巡检报告
                sql = new StringBuffer ();
                sql.append ( " SELECT " );
                sql.append ( "	cm.`name` AS cmName, ip.plan_id AS planId," );
                sql.append ( " 	IFNULL(ir.house_name, '无') AS houseName, IFNULL(ir.cm_actual_name, '无') AS cmActualName,  " );
                sql.append ( " 	IFNULL(ir.cm_actual_addr, '无') AS cmActualAddr, IFNULL(ir.inp_con_user, '无') AS inpConUser,  " );
                sql.append ( " 	IFNULL(ir.inp_con_user_tel, '无') AS inpConUserTel, IFNULL(ir.yt_score_rm, '无') AS ytScoreRm,  " );
                sql.append ( " 	IFNULL(ir.yt_rm_temperature, '无') AS ytRmTemperature, IFNULL(ir.yt_rm_humidity, '无') AS ytRmHumidity,  " );
                sql.append ( " 	IFNULL(ir.yt_score_screen, '无') AS ytScoreScreen, IFNULL(ir.yt_score_ce, '无') AS ytScoreCe,  " );
                sql.append ( " 	IFNULL(ir.yt_problem, '无') AS ytProblem, IFNULL(ir.yt_is_secl_is_Illegal, '无') AS ytIsSeclIsIllegal, " );
                sql.append ( " 	IFNULL(et.type_desc, '无') AS tmsBrandVal, " );
                sql.append ( " 	CASE ir.tms_lan_conn_is_nomal WHEN '1' THEN '是' ELSE '否' END AS tmsLanConnIsNomalVal, " );
                sql.append ( " 	CASE ir.tms_dcp_trans_is_normal WHEN '1' THEN '是' ELSE '否' END AS tmsDcpTransIsNormalVal, " );
                sql.append ( " 	CASE ir.tms_pe_control_is_normal WHEN '1' THEN '是' ELSE '否' END AS tmsPeControlIsNormalVal, " );
                sql.append ( " 	CASE ir.tms_sl_schedule_is_normal WHEN '1' THEN '是' ELSE '否' END AS tmsSlScheduleIsNormalVal, " );
                sql.append ( " 	ir.server_brand_other AS serverBrandOther, IFNULL(et1.type_desc, '无') AS serverBrandVal, IFNULL(ir.server_model, '无') AS serverModel,  " );
                sql.append ( " 	IFNULL(ir.qj_score_overall, '无') AS qjScoreOverall, IFNULL(ir.qj_score_dust_filter, '无') AS qjScoreDustFilter,  " );
                sql.append ( " 	IFNULL(ir.qj_score_aire_inlet, '无') AS qjScoreAireInlet, IFNULL(ir.qj_score_ele_box, '无') AS qjScoreEleBox,  " );
                sql.append ( " 	IFNULL(ir.gx_score_cam_lens, '无') AS gxScoreCamLens, IFNULL(ir.gx_cam_lens, '无') AS gxCamLens,  " );
                sql.append ( " 	IFNULL(ir.gx_score_reflective_lens, '无') AS gxScoreReflectiveLens, IFNULL(ir.gx_score_light_path, '无') AS gxScoreLightPath,  " );
                sql.append ( " 	IFNULL(tp.typename, '无') AS gxLightPathVal," );
                sql.append ( "	CONCAT(" );
                sql.append ( "		IF (FIND_IN_SET(1, gx_light_path_charges_mp) > 0 ,'光管翻新,', '')," );
                sql.append ( "		IF (FIND_IN_SET(2, gx_light_path_charges_mp) > 0 ,'引擎翻新,', '')," );
                sql.append ( "		IF (FIND_IN_SET(3, gx_light_path_charges_mp) > 0 ,'深度清洁', '')" );
                sql.append ( "	) AS gxLightPathChargesMpVal, " );
                sql.append ( " 	IFNULL(ir.lq_score_vent_speed, '无') AS lqScoreVentSpeed, IFNULL(ir.lq_score_coolant, '无') AS lqScoreCoolant,  " );
                sql.append ( " 	IFNULL(ir.lq_score_running_state, '无') AS lqScoreRunningState, IFNULL(ir.lq_is_leak_liquid, '无') AS lqIsLeakLiquid, " );
                sql.append ( " 	IFNULL(ir.lq_is_insulation, '无') AS lqIsInsulation, IFNULL(ir.gy_dryer_cw_is_normal, '无') AS gyDryerCwIsNormal, " );
                sql.append ( " 	IFNULL(ir.gy_laser_is_normal, '无') AS gyLaserIsNormal, IFNULL(ir.xd_score_xn,'无') AS xdScoreXn,  " );
                sql.append ( " 	IFNULL(ir.xd_brand,'无') AS xdBrand, IFNULL(ir.xd_score_joints,'无') AS xdScoreJoints,  " );
                sql.append ( " 	IFNULL(ir.xl_score_ac,'无') AS xlScoreAc, IFNULL(ir.xl_score_voltage,'无') AS xlScoreVoltage,  " );
                sql.append ( " 	IFNULL(ir.yx_score_focus,'无') AS yxScoreFocus, IFNULL(ir.yx_score_frame,'无') AS yxScoreFrame,  " );
                sql.append ( " 	IFNULL(ir.yx_light_c,'无') AS yxLightC, IFNULL(ir.yx_light_left,'无') AS yxLightLeft,  " );
                sql.append ( " 	IFNULL(ir.yx_light_center,'无') AS yxLightCenter, IFNULL(ir.yx_light_right,'无') AS yxLightRight,  " );
                sql.append ( " 	IFNULL(ir.yx_score_3d,'无') AS yxScore3d,  " );
                sql.append ( " 	CASE ir.yx_3d_type WHEN '1' THEN '双机偏振' WHEN '2' THEN '主动' WHEN '3' THEN 'RealD' WHEN '4' THEN 'Dolby' ELSE '无' END  AS yx3dTypeVal, " );
                sql.append ( " 	IFNULL(ir.yx_3d_light, '无') AS yx3dLight, " );
                sql.append ( " 	CASE ir.fwq_hd_space_speed_mp WHEN '1' THEN '维修' WHEN '2' THEN '清理' WHEN '3' THEN '合格' ELSE '无' END AS fwqHdSpaceSpeedMpVal, " );
                sql.append ( " 	CASE ir.fwq_time_calibration_mp WHEN '1' THEN '校准' WHEN '2' THEN '正确' ELSE '无' END AS fwqTimeCalibrationMpVal, " );
                sql.append ( " 	IFNULL(ir.score_projector_mb, '无') AS scoreProjectorMb,  " );
                sql.append ( " 	CASE ir.projector_mb_mp WHEN 'on' THEN '暂无' ELSE '有' END AS projectorMbMpVal, " );
                sql.append ( " 	IFNULL(ir.before_score, '无') AS beforeScore, IFNULL(ir.after_score, '无') AS afterScore,  " );
                sql.append ( " 	IFNULL(ir.remark, '无') AS remark, IFNULL(ir.training_num, '无') AS trainingNum,  " );
                sql.append ( " 	IFNULL(ir.training_score, '无') AS trainingScore, IFNULL(ir.comprehensive_evaluation, '无') AS comprehensiveEvaluation " );
                sql.append ( " FROM  " );
                sql.append ( " 	zy_inspection_plan ip  " );
                sql.append ( " LEFT JOIN zy_equipment_spare es on es.id = ip.equipment_spare_id " );
                sql.append ( " LEFT JOIN zy_cinema cm on cm.id = es.belong_cinema_id " );
                sql.append ( " LEFT JOIN zy_inspection_report ir ON ir.inspection_plan_id = ip.id " );
                sql.append ( " LEFT JOIN zy_equipment_type et on et.id = ir.tms_brand " );
                sql.append ( " LEFT JOIN zy_equipment_type et1 on et1.id = ir.server_brand " );
                sql.append ( " LEFT JOIN t_s_typegroup tg on tg.typegroupcode = '" ).append ( StaticValue.DIC_LIGHT_PATH ).append ( "' " );
                sql.append ( " LEFT JOIN t_s_type tp on tp.typecode = ir.gx_light_path AND tg.id = tp.typegroupid " );
                sql.append ( " WHERE " );
                sql.append ( " 	ip.id = '" ).append ( ipId ).append ( "' " );
                rsMap.put ( "ipReport", super.findOneForJdbc ( sql.toString () ) );

                sql = new StringBuffer ();
                sql.append ( " SELECT " );
                sql.append ( " 	ra.file_log_id " );
                sql.append ( " FROM " );
                sql.append ( " 	zy_report_attachment ra " );
                sql.append ( " LEFT JOIN zy_inspection_report ir on ir.id = ra.report_id " );
                sql.append ( " left JOIN zy_inspection_plan ip on ip.id = ir.inspection_plan_id " );
                sql.append ( " WHERE " );
                sql.append ( " 	ip.id = '" ).append ( ipId ).append ( "' " );
                sql.append ( " AND ra.type = ? " );

                rsMap.put ( "irCompletion", super.findForJdbc ( sql.toString (), StaticValue.DIC_REPORT_ATTACH_TYPE_COMPLETION_IMAGE ) );//巡检报告 完工单附件
                rsMap.put ( "irInspection", super.findForJdbc ( sql.toString (), StaticValue.DIC_REPORT_ATTACH_TYPE_INSPECTION_IMAGE ) );//巡检报告 巡检图片附件
            }
            //巡检评价
            sql = new StringBuffer ();
            sql.append ( " SELECT " );
            sql.append ( " 	cie.id cieId, cm.`name` AS cmName, DATE_FORMAT(cie.create_date,'%Y-%m-%d %H:%i:%s') AS cieUpdateDate, cie.opinion, " );
            sql.append ( " 	cie.last_evaluate AS lastEvaluate, cie.service_evaluate AS serviceEvaluate, cie.talk_evaluate AS talkEvaluate, " );
            sql.append ( " 	cie.effect_evaluate AS effectEvaluate ,cie.train_evaluate AS trainEvaluate, cie.effect_evaluate AS effectEvaluate, cie.skill_evaluate AS skillEvaluate " );
            sql.append ( " FROM " );
            sql.append ( " 	cbs_inspection_evaluate cie " );
            sql.append ( " LEFT JOIN zy_inspection_plan ip on ip.id = cie.inspection_id " );
            sql.append ( " LEFT JOIN zy_equipment_spare es on es.id = ip.equipment_spare_id " );
            sql.append ( " LEFT JOIN zy_cinema cm on cm.id = es.belong_cinema_id " );
            sql.append ( " WHERE " );
            sql.append ( "	cie.evaluate_state <> '" ).append ( StaticValue.DIC_EVALUATE_STATE_0 ).append ( "' " );
            sql.append ( " 	AND cie.inspection_id = '" ).append ( ipId ).append ( "' " );
            rsMap.put ( "ipEvaluate", super.findOneForJdbc ( sql.toString () ) );
        }
        return rsMap;
    }

    @Override
    public List<Map<String, Object>> queryEsOrCm(HttpServletRequest req) {
        String searchContent = oConvertUtils.getString ( req.getParameter ( "searchContent" ) );
        StringBuffer sql = new StringBuffer ();
        sql.append ( " SELECT " );
        sql.append ( " 	'1' AS type, " );
        sql.append ( " 	cm.id, " );
        sql.append ( " 	cm.name AS title " );
        sql.append ( " FROM " );
        sql.append ( " 	zy_cinema cm " );
        sql.append ( " WHERE " );
        sql.append ( " 	cm.`name` LIKE '%" ).append ( searchContent ).append ( "%' " );
        sql.append ( "  " );
        sql.append ( " UNION " );
        sql.append ( "  " );
        sql.append ( " SELECT " );
        sql.append ( " 	'2' AS type, " );
        sql.append ( " 	es.sn AS id, " );
        sql.append ( " 	es.sn AS title " );
        sql.append ( " FROM " );
        sql.append ( " 	zy_equipment_spare es " );
        sql.append ( " WHERE " );
        sql.append ( " 	es.sn = '" ).append ( searchContent ).append ( "' " );
        return super.findForJdbc ( sql.toString () );
    }

    @Override
    public List<Map<String, Object>> queryCmForAppEsChange(HttpServletRequest req) {
        String searchContent = oConvertUtils.getString ( req.getParameter ( "searchContent" ) );
        StringBuffer sql = new StringBuffer ();
        sql.append ( " SELECT" );
        sql.append ( " 	cm.id, cm.`name`" );
        sql.append ( " FROM" );
        sql.append ( " 	zy_cinema cm" );
        sql.append ( " WHERE" );
        sql.append ( " 	cm.`name` LIKE '%" ).append ( searchContent ).append ( "%'" );
        return super.findForJdbc ( sql.toString () );
    }


    @Override
    public Map<String, Object> appEgSignInDetial(HttpServletRequest req) {
        String ipId = oConvertUtils.getString ( req.getParameter ( "ipId" ) );
        StringBuffer sql = new StringBuffer ();
        sql.append ( " SELECT " );
        sql.append ( " 	ip.id, tp.typename AS stateVal, ip.plan_id AS planId, peg.`name` AS aegName,peg.cellphone AS aegCellphone,  " );
        sql.append ( " 	eg.`name` AS egName, eg.cellphone AS egCellphone, es.sn, cm.`name` AS cmName, ct.`name` AS cmCtName, " );
        sql.append ( " 	ip.company," );
        sql.append ( " 	DATE_FORMAT(es.last_year_inspection_date,'%Y-%m-%d') AS lastYearIpDateVal, " );
        sql.append ( " 	CASE es.laser_reconstruction WHEN 1 THEN '是' ELSE '否' END AS laserVal, " );
        sql.append ( " 	tp_1.typename AS lightPathVal, ip.remarks " );
        sql.append ( " FROM  " );
        sql.append ( " zy_inspection_plan ip  " );
        sql.append ( " LEFT JOIN t_s_typegroup tg on tg.typegroupcode = '" ).append ( StaticValue.DIC_PLAN_STATE ).append ( "' " );
        sql.append ( " LEFT JOIN t_s_type tp on tp.typecode = ip.state " );
        sql.append ( " LEFT JOIN zy_engineer eg on eg.id = ip.engineer " );
        sql.append ( " LEFT JOIN zy_engineer peg on peg.id = eg.parent_id " );
        sql.append ( " LEFT JOIN zy_equipment_spare es on es.id = ip.equipment_spare_id " );
        sql.append ( " LEFT JOIN zy_cinema cm on cm.id = es.belong_cinema_id " );
        sql.append ( " LEFT JOIN zy_contacts ct ON ct.belong_cinema = cm.id " );
        sql.append ( " 	AND ct.state = '" ).append ( StaticValue.DIC_ENGINEER_STATE_ONJOB ).append ( "' " );
        sql.append ( " 	AND ct.is_delete = 0 " );
        sql.append ( " 	AND ct.type = '" ).append ( StaticValue.DIC_CONTACT_TYPE_CINEMA_CONTACT ).append ( "' " );
        sql.append ( " 	AND ct.con_business LIKE '%" ).append ( StaticValue.DIC_BUS_SCOPE_INSPECTION ).append ( "%' " );
        sql.append ( " LEFT JOIN t_s_depart dp on dp.org_code = ip.company " );
        sql.append ( " LEFT JOIN zy_contacts ct_1 on ct_1.base_id = ip.charge_person " );
        sql.append ( " LEFT JOIN t_s_typegroup tg_1 on tg_1.typegroupcode = '" ).append ( StaticValue.DIC_LIGHT_PATH ).append ( "' " );
        sql.append ( " LEFT JOIN t_s_type tp_1 on tp_1.typecode = ip.light_path " );
        sql.append ( "	WHERE ip.id = '" ).append ( ipId ).append ( "' " );
        Map<String, Object> signInDetailMap = super.findForJdbc ( sql.toString () ).get ( 0 );//这里因为 影院的联系人 和影院技术主管可能存在多个人。所以用 get 0
        sql = new StringBuffer ();
        sql.append ( " SELECT " );
        sql.append ( " 	dp.shortname AS ipCompanyName, ct.`name` AS ipCtName, ct.cellphone1 AS ipCtCellphone1,ct.cellphone2 AS ipCtCellphone2 " );
        sql.append ( " FROM " );
        sql.append ( " 	t_s_base_user bu " );
        sql.append ( " LEFT JOIN zy_contacts ct on ct.base_id = bu.ID " );
        sql.append ( " LEFT JOIN t_s_user_org uo on uo.user_id = bu.ID " );
        sql.append ( " LEFT JOIN t_s_depart dp on dp.ID = uo.org_id " );
        sql.append ( " LEFT JOIN t_s_role_user ru on ru.userid = bu.ID " );
        sql.append ( " LEFT JOIN t_s_role ro on ro.ID = ru.roleid  " );
        sql.append ( " 	WHERE " );
        sql.append ( " dp.org_code = '" ).append ( signInDetailMap.get ( "company" ).toString () ).append ( "' " );
        sql.append ( " AND dp.logic_delete = 0 " );
        sql.append ( " AND ro.rolecode = '" ).append ( StaticValue.RULE_CODE_THIRDPARTY_HEADER ).append ( "' " );
        sql.append ( " AND ct.position = '" ).append ( StaticValue.DIC_CONTACT_POSITION_TP_SERVER_BUSINESSR ).append ( "' " );
        sql.append ( " AND ct.is_delete = '0' " );
        sql.append ( " AND ct.state = '" ).append ( StaticValue.DIC_ENGINEER_STATE_ONJOB ).append ( "' " );
        sql.append ( " AND dp.bus_scope LIKE '%" ).append ( StaticValue.DIC_LINK_BUSINESS_INSPECTION ).append ( "%' " );
        List<Map<String, Object>> inspectionCtMaps = super.findForJdbc ( sql.toString () );
        if (null != inspectionCtMaps && inspectionCtMaps.size () > 0) {
            signInDetailMap.putAll ( inspectionCtMaps.get ( 0 ) );
        }
        return signInDetailMap;
    }

    @Override
    public Map<String, Object> queryIpDetailOfEg(String ipId) {
        Map<String, Object> rsMap = new HashMap<String, Object> ();
        StringBuffer sql = new StringBuffer ();
        //巡检详情
        sql.append ( " SELECT " );
        sql.append ( " 	es.sn, ip.id AS ipId, ip.plan_id AS planId, MONTH(ip.ip_plan_date) AS ipMonth,tp_1.typename AS lightPathVal,ip.remarks, ip.engineer_order_time_count AS egOrderTimeUdtCount, " );
        sql.append ( "	IFNULL(DATE_FORMAT(ip.end_time,'%Y-%m-%d'),'无') AS endTime," );
        sql.append ( "	DATE_FORMAT(ip.engineer_order_time,'%Y-%m-%d') AS engineerOrderTime, " );
        sql.append ( "	IFNULL(ip.company_had_area_eg,'0') AS companyHadAreaEgVal, IFNULL(DATE_FORMAT(ip.engineer_order_time,'%Y-%m-%d'),'无') AS engineerOrderTime, " );
        sql.append ( " 	rm.room_num AS roomNum, et.type_desc AS esTypeDesc, es.laser_reconstruction AS laser, " );
        sql.append ( "	CASE es.laser_reconstruction WHEN '1' THEN '是' ELSE '否' END AS laserVal, IFNULL(DATE_FORMAT(es.last_year_inspection_date,'%Y-%m-%d'),'无') AS lastYearInspectionDate, " );
        sql.append ( " 	IF(TIMESTAMPDIFF(DAY,NOW(),es.repair_end_date) < 0 ,'保外','保内') AS inReparirDateVal, " );
        sql.append ( "	CASE tp_2.typecode WHEN '" ).append ( StaticValue.DIC_SERVER_STATE_1001 ).append ( "' THEN '1' ELSE '0' END AS inServer, " );
        sql.append ( "	CASE ip.state WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY ).append ( "' THEN '1' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED ).append ( "' THEN '2' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_REFUSED ).append ( "' THEN '3' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_ASSIGNED ).append ( "' THEN '4' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_REFUSED ).append ( "' THEN '5' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED ).append ( "' THEN '6' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED ).append ( "' THEN '7' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT ).append ( "' THEN '8' " );
        sql.append ( "		WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE ).append ( "' THEN '9' END AS ipState, " );
        sql.append ( " 	tp_2.typename AS serverStateVal, cm.id AS cmId, cm.`name` AS cmName, cm.address, tt.territoryname, ptt.territoryname AS pTerritoryname, IFNULL(dp.departname,'无') AS departname, " );
        sql.append ( "	ct.`name` AS tecDirectorName, ct.cellphone1 AS tecDirectorCellphone, ct_1.`name` AS ipCtName, ct_1.cellphone1 AS ipCtCellphone " );
        sql.append ( " FROM " );
        sql.append ( " 	zy_inspection_plan ip " );
//        sql.append(" LEFT JOIN t_s_typegroup tg ON tg.typegroupcode = '").append(StaticValue.DIC_PLAN_INSPECTION_QUARTER).append("' ");
//        sql.append(" LEFT JOIN t_s_type tp ON tp.typecode = ip.plan_quarter AND tg.ID = tp.typegroupid ");
        sql.append ( " LEFT JOIN t_s_typegroup tg_1 ON tg_1.typegroupcode = '" ).append ( StaticValue.DIC_LIGHT_PATH ).append ( "' " );
        sql.append ( " LEFT JOIN t_s_type tp_1 ON tp_1.typecode = ip.light_path AND tg_1.ID = tp_1.typegroupid " );
        sql.append ( " LEFT JOIN zy_equipment_spare es ON es.id = ip.equipment_spare_id " );
        sql.append ( " LEFT JOIN t_s_typegroup tg_2 ON tg_2.typegroupcode = '" ).append ( StaticValue.DIC_SERVER_STATE ).append ( "' " );
        sql.append ( " LEFT JOIN t_s_type tp_2 ON tp_2.typecode = es.server_state AND tg_2.ID = tp_2.typegroupid " );
        sql.append ( " LEFT JOIN zy_equipment_type et ON et.id = es.type " );
        sql.append ( " LEFT JOIN zy_cinema cm ON cm.id = es.belong_cinema_id " );
        sql.append ( " LEFT JOIN t_s_territory tt ON tt.ID = cm.province " );
        sql.append ( " LEFT JOIN t_s_territory ptt ON ptt.ID = tt.territoryparentid " );
        sql.append ( " LEFT JOIN t_s_depart dp ON dp.id = cm.belong_org " );
        sql.append ( " LEFT JOIN zy_room rm ON rm.id = es.house " );
        sql.append ( " LEFT JOIN zy_contacts ct ON ct.belong_cinema = cm.id " );
        sql.append ( " 	AND ct.state = '" ).append ( StaticValue.DIC_ENGINEER_STATE_ONJOB ).append ( "' " );
        sql.append ( " 	AND ct.is_delete = 0 " );
        sql.append ( " 	AND ct.type = '" ).append ( StaticValue.DIC_CONTACT_TYPE_CINEMA_CONTACT ).append ( "' " );
        sql.append ( " 	AND ct.position = '" ).append ( StaticValue.DIC_CONTACT_POSITION_C_TECHNICAL_DIRECTOR ).append ( "' " );
        sql.append ( " LEFT JOIN zy_contacts ct_1 on ct_1.belong_cinema = cm.id " );
        sql.append ( " 	AND ct_1.state = '" ).append ( StaticValue.DIC_ENGINEER_STATE_ONJOB ).append ( "' " );
        sql.append ( " 	AND ct_1.is_delete = 0 " );
        sql.append ( " 	AND ct_1.type = '" ).append ( StaticValue.DIC_CONTACT_TYPE_CINEMA_CONTACT ).append ( "' " );
        sql.append ( " 	AND ct_1.con_business LIKE '%" ).append ( StaticValue.DIC_BUS_SCOPE_INSPECTION ).append ( "%' " );
        sql.append ( " WHERE " );
        sql.append ( " 	ip.id = '" ).append ( ipId ).append ( "' " );
        Map<String, Object> ipDetailMap = super.findForJdbc ( sql.toString () ).size()>0?super.findForJdbc ( sql.toString () ).get ( 0 ):null;//这里因为 影院的联系人 和影院技术主管可能存在多个人。所以用 get 0
        rsMap.put ( "ipDetail", ipDetailMap );


//		工程师这里不需要显示 最后的操作人
//		sql = new StringBuffer();
//		sql.append(" SELECT ");
//		sql.append(" 	pr.create_name AS createName, ");
//		sql.append(" 	pr.remark ");
//		sql.append(" FROM ");
//		sql.append(" 	zy_plan_record pr ");
//		sql.append(" WHERE ");
//		sql.append(" 	pr.bus_id = '").append(ipId).append("' ");
//		sql.append(" ORDER BY ");
//		sql.append(" 	pr.create_date DESC ");
//		sql.append(" LIMIT 1 ");
//		rsMap.put("ipLastRecord", super.findOneForJdbc(sql.toString()));//巡检计划记录，配合巡检状态显示，不同于下面的巡检查询

        //巡检进度
        sql = new StringBuffer ();
        sql.append ( " SELECT " );
        sql.append ( " 	pr.remark, DATE_FORMAT(pr.create_date,'%Y-%m-%d %H:%i:%s') AS createDate, " );
        sql.append ( "	CASE pr.plan_state WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE ).append ( "' THEN '1' ELSE '0' END AS isDone " );
        sql.append ( " FROM " );
        sql.append ( " 	zy_plan_record pr " );
        sql.append ( " WHERE " );
        sql.append ( " 	bus_id = '" ).append ( ipId ).append ( "' " );
        sql.append ( " ORDER BY pr.create_date " );
        rsMap.put ( "ipRecord", super.findForJdbc ( sql.toString () ) );

        //巡检报告
        ZyInspectionReportEntity zyIr = super.findUniqueByProperty ( ZyInspectionReportEntity.class, "inspectionPlanId", ipId );
        if (null != zyIr) {
            sql = new StringBuffer ();
            sql.append ( " SELECT " );
            sql.append ( "	ip.id AS ipId, ir.id AS irId, " );
            sql.append ( "	cm.`name` AS cmName, ip.plan_id AS planId," );
            sql.append ( " 	IFNULL(ir.house_name, '无') AS houseName, IFNULL(ir.cm_actual_name, '无') AS cmActualName,  " );
            sql.append ( " 	IFNULL(ir.cm_actual_addr, '无') AS cmActualAddr, IFNULL(ir.inp_con_user, '无') AS inpConUser,  " );
            sql.append ( " 	IFNULL(ir.inp_con_user_tel, '无') AS inpConUserTel, IFNULL(ir.yt_score_rm, '无') AS ytScoreRm,  " );
            sql.append ( " 	IFNULL(ir.yt_rm_temperature, '无') AS ytRmTemperature, IFNULL(ir.yt_rm_humidity, '无') AS ytRmHumidity,  " );
            sql.append ( " 	IFNULL(ir.yt_score_screen, '无') AS ytScoreScreen, IFNULL(ir.yt_score_ce, '无') AS ytScoreCe,  " );
            sql.append ( " 	IFNULL(ir.yt_problem, '无') AS ytProblem, IFNULL(ir.yt_is_secl_is_Illegal, '无') AS ytIsSeclIsIllegal, " );
            sql.append ( " 	ir.tms_brand AS tmsBrand, IFNULL(et.type_desc, '无') AS tmsBrandVal, " );
            sql.append ( " 	CASE ir.tms_lan_conn_is_nomal WHEN '1' THEN '是' ELSE '否' END AS tmsLanConnIsNomalVal, " );
            sql.append ( " 	CASE ir.tms_dcp_trans_is_normal WHEN '1' THEN '是' ELSE '否' END AS tmsDcpTransIsNormalVal, " );
            sql.append ( " 	CASE ir.tms_pe_control_is_normal WHEN '1' THEN '是' ELSE '否' END AS tmsPeControlIsNormalVal, " );
            sql.append ( " 	CASE ir.tms_sl_schedule_is_normal WHEN '1' THEN '是' ELSE '否' END AS tmsSlScheduleIsNormalVal, " );
            sql.append ( " 	ir.server_brand AS serverBrand, ir.server_brand_other AS serverBrandOther, IFNULL(et1.type_desc, '无') AS serverBrandVal, IFNULL(ir.server_model, '无') AS serverModel,  " );
            sql.append ( " 	IFNULL(ir.qj_score_overall, '无') AS qjScoreOverall, IFNULL(ir.qj_score_dust_filter, '无') AS qjScoreDustFilter,  " );
            sql.append ( " 	IFNULL(ir.qj_score_aire_inlet, '无') AS qjScoreAireInlet, IFNULL(ir.qj_score_ele_box, '无') AS qjScoreEleBox,  " );
            sql.append ( " 	IFNULL(ir.gx_score_cam_lens, '无') AS gxScoreCamLens, IFNULL(ir.gx_cam_lens, '无') AS gxCamLens,  " );
            sql.append ( " 	IFNULL(ir.gx_score_reflective_lens, '无') AS gxScoreReflectiveLens, IFNULL(ir.gx_score_light_path, '无') AS gxScoreLightPath,  " );
            sql.append ( " 	IFNULL(tp.typename, '无') AS gxLightPathVal," );
            sql.append ( "	CONCAT(" );
            sql.append ( "		IF (FIND_IN_SET(1, gx_light_path_charges_mp) > 0 ,'光管翻新,', '')," );
            sql.append ( "		IF (FIND_IN_SET(2, gx_light_path_charges_mp) > 0 ,'引擎翻新,', '')," );
            sql.append ( "		IF (FIND_IN_SET(3, gx_light_path_charges_mp) > 0 ,'深度清洁', '')" );
            sql.append ( "	) AS gxLightPathChargesMpVal, " );
            sql.append ( " 	IFNULL(ir.lq_score_vent_speed, '无') AS lqScoreVentSpeed, IFNULL(ir.lq_score_coolant, '无') AS lqScoreCoolant,  " );
            sql.append ( " 	IFNULL(ir.lq_score_running_state, '无') AS lqScoreRunningState, IFNULL(ir.lq_is_leak_liquid, '无') AS lqIsLeakLiquid, " );
            sql.append ( " 	IFNULL(ir.lq_is_insulation, '无') AS lqIsInsulation, IFNULL(ir.gy_dryer_cw_is_normal, '无') AS gyDryerCwIsNormal, " );
            sql.append ( " 	IFNULL(ir.gy_laser_is_normal, '无') AS gyLaserIsNormal, IFNULL(ir.xd_score_xn,'无') AS xdScoreXn,  " );
            sql.append ( " 	IFNULL(ir.xd_brand,'无') AS xdBrand, IFNULL(ir.xd_score_joints,'无') AS xdScoreJoints,  " );
            sql.append ( " 	IFNULL(ir.xl_score_ac,'无') AS xlScoreAc, IFNULL(ir.xl_score_voltage,'无') AS xlScoreVoltage,  " );
            sql.append ( " 	IFNULL(ir.yx_score_focus,'无') AS yxScoreFocus, IFNULL(ir.yx_score_frame,'无') AS yxScoreFrame,  " );
            sql.append ( " 	IFNULL(ir.yx_light_c,'无') AS yxLightC, IFNULL(ir.yx_light_left,'无') AS yxLightLeft,  " );
            sql.append ( " 	IFNULL(ir.yx_light_center,'无') AS yxLightCenter, IFNULL(ir.yx_light_right,'无') AS yxLightRight,  " );
            sql.append ( " 	IFNULL(ir.yx_score_3d,'无') AS yxScore3d,  " );
            sql.append ( " 	CASE ir.yx_3d_type WHEN '1' THEN '双机偏振' WHEN '2' THEN '主动' WHEN '3' THEN 'RealD' WHEN '4' THEN 'Dolby' ELSE '无' END  AS yx3dTypeVal, " );
            sql.append ( " 	IFNULL(ir.yx_3d_light, '无') AS yx3dLight, " );
            sql.append ( " 	CASE ir.fwq_hd_space_speed_mp WHEN '1' THEN '维修' WHEN '2' THEN '清理' WHEN '3' THEN '合格' ELSE '无' END AS fwqHdSpaceSpeedMpVal, " );
            sql.append ( " 	CASE ir.fwq_time_calibration_mp WHEN '1' THEN '校准' WHEN '2' THEN '正确' ELSE '无' END AS fwqTimeCalibrationMpVal, " );
            sql.append ( " 	IFNULL(ir.score_projector_mb, '无') AS scoreProjectorMb,  " );
            sql.append ( " 	CASE ir.projector_mb_mp WHEN 'on' THEN '暂无' ELSE '有' END AS projectorMbMpVal, " );
            sql.append ( " 	IFNULL(ir.before_score, '无') AS beforeScore, IFNULL(ir.after_score, '无') AS afterScore,  " );
            sql.append ( " 	IFNULL(ir.remark, '无') AS remark, IFNULL(ir.training_num, '无') AS trainingNum,  " );
            sql.append ( " 	IFNULL(ir.training_score, '无') AS trainingScore, IFNULL(ir.comprehensive_evaluation, '无') AS comprehensiveEvaluation, " );

            sql.append ( "	ir.eng_item_id AS engItemId, ir.eng_item_sn AS engItemSn, ir.eng_security_sn AS engSecuritySn, ir.eng_exception_sign AS engExceptionSign," ); // 备件
            sql.append ( "	ir.ti_icp_item_id AS tiIcpItemId, ir.ti_icp_item_sn AS tiIcpItemSn, ir.ti_icp_security_sn AS tiIcpSecuritySn, ir.ti_icp_exception_sign AS tiIcpExceptionSign," );
            sql.append ( "	ir.lps_item_id AS lpsItemId, ir.lps_item_sn AS lpsItemSn, ir.lps_security_sn AS lpsSecuritySn," +
                    " ir.lps2_item_sn AS lps2ItemSn, ir.lps2_security_sn AS lps2SecuritySn, " +
                    " ir.lps3_item_sn AS lps3ItemSn, ir.lps3_security_sn AS lps3SecuritySn, ir.lps_exception_sign AS lpsExceptionSign," );
            sql.append ("   ir.ldm_Item_id AS ldmItemId, ");
            sql.append ("   ir.ldm1_sn AS ldm1ItemSn, ");
            sql.append ("   ir.ldm1_security_sn AS ldm1SecuritySn, ");
            sql.append ("   ir.ldm2_sn AS ldm2ItemSn, ");
            sql.append ("   ir.ldm2_security_sn AS ldm2SecuritySn, ");
            sql.append ("   ir.ldm_exception_sign AS ldmExceptionSign, ");
            sql.append ( "	ir.enigma_item_id AS enigmaItemId, ir.enigma_item_sn AS enigmaItemSn, ir.enigma_security_sn AS enigmaSecuritySn, ir.enigma_exception_sign AS enigmaExceptionSign," );
            sql.append ( "	ir.controler_item_id AS controlerItemId, ir.controler_item_sn AS controlerItemSn, ir.controler_security_sn AS controlerSecuritySn, ir.controler_exception_sign AS controlerExceptionSign," );
            sql.append ( "	ir.smps_item_id AS smpsItemId, ir.smps_item_sn AS smpsItemSn, ir.smps_security_sn AS smpsSecuritySn, ir.smps_excption_sign AS smpsExcptionSign, " );
            sql.append ( "	ir.touch_item_id AS touchItemId, ir.touch_item_sn AS touchItemSn, ir.touch_security_sn AS touchSecuritySn, ir.touch_exception_sign AS touchExcptionSign, " );
            sql.append ( "	ir.create_name AS createName, ir.create_by AS createBy, IFNULL(DATE_FORMAT(ir.create_date,'%Y-%m-%d %T'),'') AS createDate, " );
            sql.append ( "	ir.update_name AS updateName, ir.update_by AS updateBy, IFNULL(DATE_FORMAT(ir.update_date,'%Y-%m-%d %T'),'') AS updateDate " );
            sql.append ( " FROM  " );
            sql.append ( " 	zy_inspection_plan ip  " );
            sql.append ( " LEFT JOIN zy_equipment_spare es on es.id = ip.equipment_spare_id " );
            sql.append ( " LEFT JOIN zy_cinema cm on cm.id = es.belong_cinema_id " );
            sql.append ( " LEFT JOIN zy_inspection_report ir ON ir.inspection_plan_id = ip.id " );
            sql.append ( " LEFT JOIN zy_equipment_type et on et.id = ir.tms_brand " );
            sql.append ( " LEFT JOIN zy_equipment_type et1 on et1.id = ir.server_brand " );
            sql.append ( " LEFT JOIN t_s_typegroup tg on tg.typegroupcode = '" ).append ( StaticValue.DIC_LIGHT_PATH ).append ( "' " );
            sql.append ( " LEFT JOIN t_s_type tp on tp.typecode = ir.gx_light_path AND tg.id = tp.typegroupid " );
            sql.append ( " WHERE " );
            sql.append ( " 	ip.id = '" ).append ( ipId ).append ( "' " );
            rsMap.put ( "ipReport", super.findOneForJdbc ( sql.toString () ) );

            sql = new StringBuffer ();
            sql.append ( " SELECT " );
            sql.append ( " 	ra.file_log_id " );
            sql.append ( " FROM " );
            sql.append ( " 	zy_report_attachment ra " );
            sql.append ( " LEFT JOIN zy_inspection_report ir on ir.id = ra.report_id " );
            sql.append ( " LEFT JOIN zy_inspection_plan ip on ip.id = ir.inspection_plan_id " );
            sql.append ( " WHERE " );
            sql.append ( " 	ip.id = '" ).append ( ipId ).append ( "' " );
            sql.append ( " AND ra.type = ? " );

            rsMap.put ( "irInspection", super.findForJdbc ( sql.toString (), StaticValue.DIC_REPORT_ATTACH_TYPE_INSPECTION_IMAGE ) );//巡检报告 巡检图片附件
            rsMap.put ( "irCompletion", super.findForJdbc ( sql.toString (), StaticValue.DIC_REPORT_ATTACH_TYPE_COMPLETION_IMAGE ) );//巡检报告 完工单附件
        }
        //巡检评价
        sql = new StringBuffer ();
        sql.append ( " SELECT " );
        sql.append ( " 	cie.id cieId, cm.`name` AS cmName, DATE_FORMAT(cie.create_date,'%Y-%m-%d %H:%i:%s') AS cieUpdateDate, cie.opinion, " );
        sql.append ( " 	cie.last_evaluate AS lastEvaluate, cie.service_evaluate AS serviceEvaluate, cie.talk_evaluate AS talkEvaluate, " );
        sql.append ( " 	cie.effect_evaluate AS effectEvaluate ,cie.train_evaluate AS trainEvaluate, cie.effect_evaluate AS effectEvaluate, cie.skill_evaluate AS skillEvaluate " );
        sql.append ( " FROM " );
        sql.append ( " 	cbs_inspection_evaluate cie " );
        sql.append ( " LEFT JOIN zy_inspection_plan ip on ip.id = cie.inspection_id " );
        sql.append ( " LEFT JOIN zy_equipment_spare es on es.id = ip.equipment_spare_id " );
        sql.append ( " LEFT JOIN zy_cinema cm on cm.id = es.belong_cinema_id " );
        sql.append ( " WHERE " );
        sql.append ( "	cie.evaluate_state <> '" ).append ( StaticValue.DIC_EVALUATE_STATE_0 ).append ( "' " );
        sql.append ( " 	AND cie.inspection_id = '" ).append ( ipId ).append ( "' " );
        rsMap.put ( "ipEvaluate", super.findOneForJdbc ( sql.toString () ) );
        return rsMap;
    }

    @SuppressWarnings("unchecked")
    @Override
    public int queryAppAegOrEgTodoIps() {
        TSUser user = ResourceUtil.getSessionUserName ();
        List<TSRoleUser> tsRoleUser = systemService.findHql ( "from TSRoleUser where TSUser.id = ?", user.getId () );
        int userType = 1;
        if (null != tsRoleUser && tsRoleUser.size () > 0) {
            for (TSRoleUser rsRU : tsRoleUser) {
                //优先级 第三方 > 区域工程师 > 工程师
                if (rsRU.getTSRole ().getRoleCode ().equals ( StaticValue.RULE_CODE_THIRDPARTY_HEADER )) {
                    userType = 1;
                    break;
                }
                if (rsRU.getTSRole ().getRoleCode ().equals ( StaticValue.RULE_CODE_AREA_ENGINEER )) {
                    userType = 2;
                    break;
                }
                if (rsRU.getTSRole ().getRoleCode ().equals ( StaticValue.RULE_CODE_THIRDPARTY_ENGINEER )) {
                    userType = 3;
                    break;
                }
            }
        }
        int todoTaskCount = 0;
        Map<String, Object> rsMap = new HashMap<String, Object> ();
        if (userType == 1) {
            rsMap = queryAppIpTpList ( 2, "", "", "", "", "" );
            if (null != rsMap.get ( "tpIpMapList_todo" ) && ((List<Map<String, Object>>) rsMap.get ( "tpIpMapList_todo" )).size () > 0) {
                for (Map<String, Object> mapList : (List<Map<String, Object>>) rsMap.get ( "tpIpMapList_todo" )) {
                    if (null != mapList && null != (List<Map<String, Object>>) mapList.get ( "dtMapList" )) {
                        todoTaskCount += ((List<Map<String, Object>>) mapList.get ( "dtMapList" )).size ();
                    }
                }
            }
        } else if (userType == 2 || userType == 3) {//区域工程师 or 工程师
            if (userType != 3) {//工程师不累加这一项
                rsMap = queryAppIpAegList ( 1, "", "", "", "", "" );
                if (null != rsMap.get ( "tpIpMapList_todo" ) && ((List<Map<String, Object>>) rsMap.get ( "tpIpMapList_todo" )).size () > 0) {
                    for (Map<String, Object> mapList : (List<Map<String, Object>>) rsMap.get ( "tpIpMapList_todo" )) {
                        if (null != mapList && null != (List<Map<String, Object>>) mapList.get ( "dtMapList" )) {
                            todoTaskCount += ((List<Map<String, Object>>) mapList.get ( "dtMapList" )).size ();
                        }
                    }
                }
            }
            rsMap = queryAppIpEgList ( 1, "", "", "", "", "" );
            if (null != rsMap.get ( "egIpMapList_todo" ) && ((List<Map<String, Object>>) rsMap.get ( "egIpMapList_todo" )).size () > 0) {
                for (Map<String, Object> mapList : (List<Map<String, Object>>) rsMap.get ( "egIpMapList_todo" )) {
                    if (null != mapList && null != (List<Map<String, Object>>) mapList.get ( "dtMapList" )) {
                        todoTaskCount += ((List<Map<String, Object>>) mapList.get ( "dtMapList" )).size ();
                    }
                }
            }
            rsMap = queryAppIpEgList ( 2, "", "", "", "", "" );
            if (null != rsMap.get ( "egIpMapList_in_service" ) && ((List<Map<String, Object>>) rsMap.get ( "egIpMapList_in_service" )).size () > 0) {
                for (Map<String, Object> mapList : (List<Map<String, Object>>) rsMap.get ( "egIpMapList_in_service" )) {
                    if (null != mapList && null != (List<Map<String, Object>>) mapList.get ( "dtMapList" )) {
                        todoTaskCount += ((List<Map<String, Object>>) mapList.get ( "dtMapList" )).size ();
                    }
                }
            }
        }

        return todoTaskCount;
    }

    private Map<String, Long> queryEgIpTasks(String egId) {
        Map<String, Long> rsMap = new HashMap<String, Long> ();
        if (StringUtil.isNotEmpty ( egId )) {
            StringBuffer selfTodoSql = new StringBuffer ();
            selfTodoSql.append ( " SELECT COUNT(1) AS total FROM " );
            selfTodoSql.append ( " 	zy_inspection_plan ip " );
            selfTodoSql.append ( " WHERE " );
            selfTodoSql.append ( "	ip.state IN (" );
            selfTodoSql.append ( "'" + StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_ASSIGNED + "'" );
            selfTodoSql.append ( " ) " );
            selfTodoSql.append ( " 	AND ip.engineer = ? " );

            StringBuffer selfDoingSql = new StringBuffer ();
            selfDoingSql.append ( " SELECT COUNT(1) AS total FROM " );
            selfDoingSql.append ( " 	zy_inspection_plan ip " );
            selfDoingSql.append ( " WHERE " );
            selfDoingSql.append ( "	ip.state IN (" );
            selfDoingSql.append ( "'" + StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED + "'," );
            selfDoingSql.append ( "'" + StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT + "'" );
            selfDoingSql.append ( "	) " );
            selfDoingSql.append ( " 	AND ip.engineer = ? " );

            long selfTodoCount = super.getCountForJdbcParam ( selfTodoSql.toString (), new Object[]{egId} );
            long selfDoingCount = super.getCountForJdbcParam ( selfDoingSql.toString (), new Object[]{egId} );
            rsMap.put ( "todo", selfTodoCount );
            rsMap.put ( "doing", selfDoingCount );
        }
        return rsMap;
    }

    @Override
    public Map<String, Object> queryEgTasks(String egId) {
        Map<String, Object> rsMap = new HashMap<String, Object> ();
        if (StringUtil.isNotEmpty ( egId )) {

            ZyEngineerEntity eg = super.getEntity ( ZyEngineerEntity.class, egId );
            if (null != eg) {
                //先查询自己的 代办 ，处理中
                Map<String, Long> egTasksMap = queryEgIpTasks ( egId );
                rsMap.put ( "selfTodoCount", egTasksMap.get ( "todo" ) );
                rsMap.put ( "selfDoingCount", egTasksMap.get ( "doing" ) );

                if (eg.getIsAreaEngineer ()) {//如果是区域工程师还要查询 子工程师的 代办，处理中
                    StringBuffer sql = new StringBuffer ();
                    sql.append ( " SELECT eg.id FROM " );
                    sql.append ( " 	zy_engineer eg " );
                    sql.append ( " WHERE " );
                    sql.append ( " 	eg.parent_id = '" ).append ( eg.getId () ).append ( "' " );
                    List<Map<String, Object>> mapList = zyCommonService.findForJdbc ( sql.toString () );
                    if (null != mapList && mapList.size () > 0) {
                        rsMap.put ( "hasChildren", true );
                        rsMap.put ( "childrenEgCount", mapList.size () );
                        long childToDoCount = 0, childDoingCount = 0;
                        for (Map<String, Object> map : mapList) {
                            Map<String, Long> chEgTasksMap = queryEgIpTasks ( map.get ( "id" ).toString () );
                            childToDoCount += chEgTasksMap.get ( "todo" );
                            childDoingCount += chEgTasksMap.get ( "doing" );
                        }
                        rsMap.put ( "childToDoCount", childToDoCount );
                        rsMap.put ( "childDoingCount", childDoingCount );
                    }
                }
            }

        }
        return rsMap;
    }

    @Override
    public void queryEngineerForAppAegSendIp(HttpServletRequest req, AjaxJson j) {
        String egName = oConvertUtils.getString ( req.getParameter ( "egName" ) );
        String planIds = oConvertUtils.getString ( req.getParameter ( "planIds" ) );
        String month = oConvertUtils.getString ( req.getParameter ( "month" ) );

        Criteria c = getSession ().createCriteria ( ZyInspectionPlanEntity.class );
        c.add ( Restrictions.in ( "id", planIds.split ( "," ) ) );
        c.add ( Restrictions.eq ( "lightPath", StaticValue.DIC_LIGHT_PATH_02 ) );
        Integer size = c.list ().size ();
        List<String> autthentications = new ArrayList<String> ();
        if (size > 0) {
            autthentications = zyCommonService.getEngineerAuthenticationsByLigthPath ( StaticValue.DIC_LIGHT_PATH_02 );
        } else {
            autthentications = zyCommonService.getEngineerAuthenticationsByLigthPath ( StaticValue.DIC_LIGHT_PATH_01 );
        }
        TSUser user = ResourceUtil.getSessionUserName ();
        StringBuffer sql = new StringBuffer ();
        sql.append ( " SELECT " );
        sql.append ( " 	eg.id, eg.`name`, eg.cellphone, eg.email, " );
        sql.append ( " 	SUM(CASE ip.state WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE ).append ( "' THEN 1 ELSE 0 END) AS 'complete', " );
        sql.append ( " 	SUM(CASE ip.state WHEN '" ).append ( StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_ASSIGNED ).append ( "' THEN 1 ELSE 0 END) AS 'aegAssigned' " );
        sql.append ( " FROM " );
        sql.append ( " 	zy_engineer eg " );
        sql.append ( " LEFT JOIN t_s_base_user bu ON bu.ID = eg.ts_base_user_id " );
        sql.append ( " LEFT JOIN zy_engineer peg ON peg.id = eg.parent_id " );
        sql.append ( " LEFT JOIN t_s_user_org uo ON uo.user_id = bu.ID " );
        sql.append ( " LEFT JOIN t_s_role_user ru ON ru.userid = bu.ID " );
        sql.append ( " LEFT JOIN t_s_role ro ON ro.ID = ru.roleid " );
        sql.append ( " LEFT JOIN zy_inspection_plan ip on ip.engineer = eg.id " );
        if (StringUtil.isNotEmpty ( month )) {
            sql.append ( " AND MONTH(ip.ip_plan_date) = '" ).append ( month ).append ( "' " );
        }
        sql.append ( " WHERE " );
        sql.append ( " 	(peg.ts_base_user_id = '" ).append ( user.getId () ).append ( "' OR eg.ts_base_user_id = '" ).append ( user.getId () ).append ( "') " );
        sql.append ( " AND ( " );
        sql.append ( " 	ro.rolecode = '" ).append ( StaticValue.RULE_CODE_THIRDPARTY_ENGINEER ).append ( "' " );
        sql.append ( " 	OR ro.rolecode = '" ).append ( StaticValue.RULE_CODE_AREA_ENGINEER ).append ( "' " );
        sql.append ( " ) " );
        sql.append ( " AND eg.state = '" ).append ( StaticValue.DIC_ENGINEER_STATE_ONJOB ).append ( "' " );
        sql.append ( " AND eg.is_delete = '0' " );
        sql.append ( " AND (" );
        for (int i = 0; i < autthentications.size (); i++) {
            if (autthentications.get ( i ) != null && StringUtil.isNotEmpty ( autthentications.get ( i ) )) {
                if (i == autthentications.size () - 1) {
                    sql.append ( " eg.authentication = '" ).append ( autthentications.get ( i ) ).append ( "')" );
                } else {
                    sql.append ( " eg.authentication = '" ).append ( autthentications.get ( i ) ).append ( "' OR" );
                }
            }
        }
        if (StringUtil.isNotEmpty ( egName )) {
            sql.append ( " AND eg.name LIKE '%" ).append ( egName ).append ( "%' " );
        }
        sql.append ( " GROUP BY eg.id " );
        j.setObj ( super.findForJdbc ( sql.toString () ) );
    }

    @Override
    public AjaxJson appEgSignIn(HttpServletRequest req, AjaxJson j) {
        String ipId = oConvertUtils.getString ( req.getParameter ( "ipId" ) );
        String reason = oConvertUtils.getString ( req.getParameter ( "reason" ) );
        try {
            if (!ipId.equals ( "" )) {
                ZyInspectionPlanEntity zyIp = super.getEntity ( ZyInspectionPlanEntity.class, ipId );
                if (null != zyIp) {
                    //记录巡检开始时间，并且变更巡检计划状态 为 工程师实施中
                    zyIp.setBeginTime ( new Date () );
                    zyIp.setState ( StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT );
                    super.saveOrUpdate ( zyIp );
                    //				if(null != zyIp.getContacter()){
                    //					zyIp.getContacter().getCellphone1();
                    //				}
                    if (!reason.equals ( "" )) {//保存APP签到未扫描SN原因
                        CbsAppSendInExEntity appSignInEx = new CbsAppSendInExEntity ();
                        appSignInEx.setPlanId ( zyIp.getId () );
                        appSignInEx.setExReason ( reason );
                        super.save ( appSignInEx );
                    }
                    //保存巡检计划流程记录
                    ZyPlanRecordEntity zyPlanRecord = new ZyPlanRecordEntity ();
                    zyPlanRecord.setBusId ( zyIp.getId () );
                    zyPlanRecord.setPlanState ( zyIp.getState () );
                    zyPlanRecord.setProcInsId ( zyIp.getProcesssId () );
                    zyPlanRecord.setRemark ( "工程师开始巡检" );
                    systemService.save ( zyPlanRecord );
                    j.setSuccess ( true );
                    j.setMsg ( "签到成功" );
                } else {
                    j.setMsg ( "没有查询到当前巡检计划" );
                    j.setSuccess ( false );
                }
            } else {
                j.setMsg ( "巡检计划ID为空" );
                j.setSuccess ( false );
            }
        } catch (Exception e) {
            e.printStackTrace ();
            j.setSuccess ( false );
            j.setMsg ( "签到异常" );
        }
        return j;
    }

    @Override
    public boolean doJudgeForEgUpdateEgOrderTime(String id, AjaxJson j, String userId) {
        ZyInspectionPlanEntity zyIP = systemService.get ( ZyInspectionPlanEntity.class, id );
        boolean flag = true;
        String message = "";
        if (null != zyIP.getEngineer () && null != zyIP.getEngineer ().getTsBaseUser () && StringUtil.isNotEmpty ( zyIP.getEngineer ().getTsBaseUser ().getId () )) {//如果其中有一项为空 则不能操作
            if (zyIP.getEngineerOrderTimeCount () > 1) {
                flag = false;
                message = "修改预约上门时间次数超过上限1次";
            } else if (!zyIP.getState ().equals ( StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED )) {
                flag = false;
                message = "当前巡检状态不能操作";
            } else if (!userId.equals ( zyIP.getEngineer ().getTsBaseUser ().getId () )) {
                flag = false;
                message = "您不能操作当前任务";
            }
        } else {
            flag = false;
            message = "您不能操作当前任务";
        }
        if (null != j) {
            j.setMsg ( message );
            j.setSuccess ( flag );
        }
        return flag;
    }


    public List<Map<String, Object>> queryPlanIdWithYear(String year) {
        String sql = "select id from zy_inspection_plan z1, " +
                "(" +
                " SELECT distinct zp.EQUIPMENT_SPARE_ID,max(create_date) as cdate " +
                " from zy_inspection_plan zp " +
                " where year(ip_plan_date) = " + (oConvertUtils.isEmpty ( year ) ? "year(now())" : "'" + year + "'" + "") +
                " group by zp.equipment_spare_id " +
                ") z2 where z1.equipment_spare_id = z2.EQUIPMENT_SPARE_ID and z1.create_date=z2.cdate ";
        logger.info ( sql );
        return findForJdbc ( sql );
    }

    public List<Map<String, Object>> queryPlanIdWithYearAndCinema(String cinemaId, String year) {
        StringBuilder sql = new StringBuilder ();
        sql.append ( "select id from zy_inspection_plan z1, (" )
                .append ( " SELECT distinct zp.EQUIPMENT_SPARE_ID,max(ip_plan_date) as cdate " )
                .append ( " from zy_inspection_plan zp,zy_equipment_spare zs " )
                .append ( " where zp.equipment_spare_id=zs.id " )
                .append ( " and zs.belong_cinema_id='" + cinemaId + "' " )
                .append ( " and year(ip_plan_date) = " + (oConvertUtils.isEmpty ( year ) ? "year(now())" : "'" + year + "'" + "") )
                .append ( " group by zp.equipment_spare_id " )
                .append ( ") z2 where z1.equipment_spare_id = z2.EQUIPMENT_SPARE_ID and z1.ip_plan_date=z2.cdate " );
        logger.info ( sql );
        return findForJdbc ( sql.toString () );
    }

    public List<ZyInspectionPlanEntity> queryPlanWithCinemaAndYear(String cinemaId, String year) {
        List<Map<String, Object>> planIds = queryPlanIdWithYearAndCinema ( cinemaId, year );
        if (planIds.size () > 0) {
            String hql = "from ZyInspectionPlanEntity zp where zp.id in ('" + (genIdsFromList ( planIds ).replace ( ",", "','" )) + "') and zp.equipmentSpare.zyCinema.id=? order by zp.ipPlanDate desc";
            logger.info ( hql );
            return findHql ( hql, cinemaId );
        }
        return new ArrayList<ZyInspectionPlanEntity> ();
    }

    public class UpdateOrdertimeReason {
        public boolean canUpdate = false;
        public String msg = "no reason";

        UpdateOrdertimeReason() {
        }

        UpdateOrdertimeReason(boolean _canUpdate, String _msg) {
            this.canUpdate = _canUpdate;
            this.msg = _msg;
        }

        public boolean isCanUpdate() {
            return canUpdate;
        }

        public void setCanUpdate(boolean canUpdate) {
            this.canUpdate = canUpdate;
        }

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }
    }

    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public UpdateOrdertimeReason checkPlanValue(ZyInspectionPlanEntity plan) {
        UpdateOrdertimeReason checkResult = new UpdateOrdertimeReason ();
        boolean flag = false;
        checkResult.setCanUpdate ( flag );
        if (plan.getEquipmentSpare () == null) {
            checkResult.setMsg ( "巡检设备为空" );
        } else if (plan.getEquipmentSpare ().getZyCinema () == null) {
            checkResult.setMsg ( "巡检设备-" + plan.getEquipmentSpare ().getSn () + "所属影院为空" );
        } else if (StringUtil.isEmpty ( plan.getCompany () )) {
            checkResult.setMsg ( "巡检服务商为空" );
        } else if (plan.getIpPlanDate () == null) {
            checkResult.setMsg ( "巡检年月为空" );
        } else if (!"1".equals ( plan.getCanUpdateOrdertime () )) {
            checkResult.setMsg ( "已修改过巡检年月" );
        } else {
            flag = true;
        }
        if (!flag) {
            return checkResult;
        }
        flag = false;
        String allowPlanState = oConvertUtils.getString ( systemService.getTypeByCode ( "plan_state_permission", "allow_state" ) );
        if (StringUtil.isNotEmpty ( allowPlanState )) {
            if (allowPlanState.contains ( plan.getState () )) {
                flag = true;
            }
        }

        if (!flag) {
            checkResult.setMsg ( "巡检计划状态不正确" );
        }
        checkResult.setCanUpdate ( flag );
        return checkResult;
    }


    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public UpdateOrdertimeReason checkIfCanUpdateEngineerOrderTime(ZyInspectionPlanEntity plan, String modifyDateString) {
        UpdateOrdertimeReason checkResult = new UpdateOrdertimeReason ();
        if (plan != null) {
            checkResult = checkPlanValue ( plan );
            if (!checkResult.isCanUpdate ()) {
                return checkResult;
            }
            String ipYear = DateUtils.formatDate ( plan.getIpPlanDate (), "yyyy" );

            if (StringUtil.isNotEmpty ( modifyDateString )) {
                if (!ipYear.equals ( modifyDateString.substring ( 0, 4 ) )) {
                    checkResult.setCanUpdate ( false );
                    checkResult.setMsg ( "巡检年月不能跨年修改" );
                    return checkResult;
                }
                /*巡检状态*/
                String inspectionSql = "from ZyInspectionPlanEntity where state=? and year(ipPlanDate)='" + ipYear + "' " +
                        "and equipmentSpare.zyCinema.id=? and company=?";
                if (findHql ( inspectionSql, StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT,
                        plan.getEquipmentSpare ().getZyCinema ().getId (), plan.getCompany () ).size () > 0) {
                    checkResult.setCanUpdate ( false );
                    checkResult.setMsg ( "计划年份中存在工程师已签到的巡检计划" );
                    return checkResult;
                }

                Date modifyDate = DateUtils.str2Date ( modifyDateString, "yyyy-MM" );

                if (DateUtils.formatDate ( plan.getIpPlanDate (), "yyyy" ).equals ( DateUtils.formatDate ( new Date (), "yyyy" ) ) &&
                        plan.getIpPlanDate ().getMonth () >= 10) {
                    checkResult.setCanUpdate ( false );
                    checkResult.setMsg ( "当年11,12月份的计划不可修改" );
                    return checkResult;
                } else {
                    Calendar c1 = Calendar.getInstance ();
                    c1.set ( Calendar.DAY_OF_MONTH, 1 );
                    Calendar modifyCal = Calendar.getInstance ();
                    modifyCal.setTime ( modifyDate );

                    if (DateUtils.dateDiff ( 'd', modifyCal, c1 ) < 60) {
                        checkResult.setCanUpdate ( false );
                        checkResult.setMsg ( "巡检年月只能调整到当前月份2个月之后" );
                        return checkResult;
                    }
                }


                /*查询否包含以下条件的计划：
                * 1.同一影院
                * 2.同一服务商
                * 3.当年（巡检年份）
                * 4.不允许修改 巡检月份（canUpdateOrdertime）
                * 5.计划状态非已完成和已取消
                * */
                String hql = "from ZyInspectionPlanEntity where state not in ('" + StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE + "','" + StaticValue.DIC_PLAN_STATE_INSPECTION_CANCEL + "')" +
                        " and canUpdateOrdertime='0' and year(ipPlanDate)='" + ipYear + "' and equipmentSpare.zyCinema.id=? and company=?";
                List<ZyInspectionPlanEntity> plans = findHql ( hql, plan.getEquipmentSpare ().getZyCinema ().getId (), plan.getCompany () );
                if (plans.size () > 0) {
                    checkResult.setCanUpdate ( false );
                    checkResult.setMsg ( "该设备所属影院同一服务商下当年有不允许修改的巡检计划" );
                    return checkResult;
                }

                /*产能检查*/
                String capacityMonth = DateUtils.formatDate ( modifyDate, "yyyy-MM-dd" );
                String maxCapacityHql = "from CbsServiceCapacityEntity where serviceProviderDepart.orgCode=? and years='" + capacityMonth + "'";
                List<CbsServiceCapacityEntity> sourceCapacity = findHql ( maxCapacityHql, plan.getCompany () );
                if (sourceCapacity.size () > 0) {
                    plans.clear ();
                    hql = "from ZyInspectionPlanEntity where state !='" + StaticValue.DIC_PLAN_STATE_INSPECTION_CANCEL + "'" +
                            " and year(ipPlanDate)=year(?) and equipmentSpare.zyCinema.id=? and company=?";
                    plans = findHql ( hql, capacityMonth, plan.getEquipmentSpare ().getZyCinema ().getId (), plan.getCompany () );
                    plans.addAll ( findToUpdateOrdertimePlan ( plan ) );
                    if (plans.size () > sourceCapacity.get ( 0 ).getMaxCapacity ()) {
                        checkResult.setCanUpdate ( false );
                        checkResult.setMsg ( "超过最大产能" );
                        return checkResult;
                    }
                } else {
                    checkResult.setCanUpdate ( false );
                    checkResult.setMsg ( plan.getContacter ().getBelongOrg ().getDepartname () + "基础数据配置有误，请拨打<a style='color:blue' href='tel:400-88-22726'>" + StaticValue.WX_BIND_MSG_REMARK + "</a>" );
                    return checkResult;
                }
            }
        }
        return checkResult;
    }

    @Override
    public UpdateOrdertimeReason updatePlanDate(ZyInspectionPlanEntity plan, String planDate) {
        UpdateOrdertimeReason result = checkIfCanUpdateEngineerOrderTime ( plan, planDate );
        if (result.isCanUpdate ()) {
            List<ZyInspectionPlanEntity> planToUpdate = findToUpdateOrdertimePlan ( plan );
            List<ZyPlanRecordEntity> records = new ArrayList<> ();
            List<Map<String, Object>> mails = new ArrayList<> ();
            List<Map<String, String>> sms = new ArrayList<> ();

            Date toPlanDate = DateUtils.str2Date ( planDate, "yyyy-MM" );
            String quarter = getIpQuarterByMonth ( oConvertUtils.getString ( toPlanDate.getMonth () + 1 ) );
            for (ZyInspectionPlanEntity updateItem : planToUpdate) {
                String origDate = updateItem.getIpPlanDate () == null ? "" : DateUtils.formatDate ( updateItem.getIpPlanDate (), "yyyy-MM" );
                ZyPlanRecordEntity rec = new ZyPlanRecordEntity ();
                rec.setBusId ( updateItem.getId () );
                rec.setRemark ( "巡检月份从:" + (null != updateItem.getIpPlanDate () ? DateUtils.formatDate ( updateItem.getIpPlanDate (), "yyyy-MM" ) : "") + " 改至:" + planDate );
                records.add ( rec );

                updateItem.setIpPlanDate ( toPlanDate );
                updateItem.setCanUpdateOrdertime ( "0" );
                updateItem.setPlanQuarter ( quarter );
                saveOrUpdate ( updateItem );

                if (updateItem.getState ().equals ( StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY )) {
                    mails.add ( buildMailWithPlan ( updateItem, origDate, planDate ) );
                } else {
                    Map param = new HashMap ();
                    param.put ( "origPlanDate", origDate );
                    param.put ( "ipPlanDate", planDate );
                    param.put ( "sn", updateItem.getEquipmentSpare ().getSn () );
                    param.put ( "cinema", plan.getEquipmentSpare ().getZyCinema ().getName () );
                    if ("1".equals ( updateItem.getCompanyHadAreaEg () ) && updateItem.getAreaEngineer () != null) {
                        param.put ( "engineer", updateItem.getAreaEngineer ().getName () );
                        param.put ( "phone", updateItem.getAreaEngineer ().getCellphone () );
                    } else {
                        if (updateItem.getEngineer () != null) {
                            param.put ( "engineer", updateItem.getEngineer ().getName () );
                            param.put ( "phone", updateItem.getEngineer ().getCellphone () );
                        }
                    }
                    sms.add ( param );
                }
            }
            result.setMsg ( "巡检年月修改成功" );
            batchSave ( records );
            if (!mails.isEmpty ()) {
                Map mail = mails.get ( 0 );
                if (null != mail.get ( "mail" )) {
                    sendMailAfterUpdateIpPlanDate ( (ZyEmailEntity) mail.get ( "mail" ), (Map) mail.get ( "param" ) );
                }
            }

            for (Map m : sms) {
                if (m.get ( "phone" ) != null) {
                    SendMessage.sendSMSFTL ( oConvertUtils.getString ( m.get ( "phone" ) ), "sms_planSendTo_engineer.ftl", m, systemService );
                }
            }

        }
        return result;
    }

    public void sendMailAfterUpdateIpPlanDate(ZyEmailEntity zmail, Map param) {
        String otherMails = oConvertUtils.getString ( systemService.getTypeByCode ( "plan_state_permission", "copy_mail_address" ) );
        if (StringUtil.isNotEmpty ( otherMails )) {
            zmail.setEmailReceiver ( zmail.getEmailReceiver () + ";" + otherMails );
        }
        SendMailUtil.sendFtlMail ( zmail, "mail_planSendTo_thirdPaty.ftl", param, systemService );
    }

    private Map<String, Object> buildMailWithPlan(ZyInspectionPlanEntity plan, String origDate, String planDate) {
        Map result = new HashMap ();
        if (plan.getContacter () != null) {
            ZyEmailEntity mail = new ZyEmailEntity ();
            mail.setEmailSubject ( "巡检年月修改通知" );
            mail.setEmailReceiver ( plan.getContacter ().getEmail () );
            result.put ( "mail", mail );
        }
        Map param = new HashMap ();
        param.put ( "company", plan.getContacter ().getBelongOrg ().getDepartname () );
        try {
            param.put ( "cinema", plan.getEquipmentSpare ().getZyCinema ().getName () );
        } catch (Exception e) {
            logger.error ( "cinema is null" );
            param.put ( "cinema", "" );
        }
        param.put ( "origPlanDate", origDate );
        param.put ( "ipPlanDate", planDate );
        result.put ( "param", param );
        param.put ( "sn", plan.getEquipmentSpare ().getSn () );
        return result;
    }

    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<ZyInspectionPlanEntity> findToUpdateOrdertimePlan(ZyInspectionPlanEntity plan) {
        String allowPlanState = oConvertUtils.getString ( systemService.getTypeByCode ( "plan_state_permission", "allow_state" ) );
        if (StringUtil.isEmpty ( allowPlanState )) {
            return null;
        }
        allowPlanState = allowPlanState.replace ( ",", "','" );
        StringBuilder hql = new StringBuilder ( "from ZyInspectionPlanEntity where state in ('" );
        hql.append ( allowPlanState )
                .append ( "')" )
                .append ( " and year(ipPlanDate)=year(?) and equipmentSpare.zyCinema.id=? and company=?" );
        return findHql ( hql.toString (), DateUtils.formatDate ( plan.getIpPlanDate () ), plan.getEquipmentSpare ().getZyCinema ().getId (), plan.getCompany () );
    }


    public String genIdsFromList(List<Map<String, Object>> source) {
        String result = "";
        for (Map<String, Object> m : source) {
            result += "," + oConvertUtils.getString ( m.get ( "id" ) );
        }
        return result.substring ( 1 );
    }

    @Override
    public void queryReportType(AjaxJson j, HttpServletRequest req) {
        String ipId = req.getParameter ( "ipId" );
        if (StringUtil.isNotEmpty ( ipId )) {
            String reportType = "5";//默认给5
            ZyInspectionPlanEntity zyIp = super.getEntity ( ZyInspectionPlanEntity.class, ipId );
            if (null != zyIp) {
                if (null != zyIp.getEquipmentSpare ().getLaserReconstruction ()
                        && zyIp.getEquipmentSpare ().getLaserReconstruction ().equals ( "1" )) {
                    reportType = "1";
                    //view = "com/zybk/zy_inspection_report/zyInspectionReport-jggz-add";//设备经过激光改造
                } else {
                    if (null != zyIp.getEquipmentSpare ().getType () && null != zyIp.getEquipmentSpare ().getType ().getEquipmentType ()) {//当前所属机型不为NULL，并且父节点不为NULL
                        if (zyIp.getEquipmentSpare ().getType ().getEquipmentType ().getTypeDesc ().equals ( "RGB激光" )) {
                            reportType = "2";
                            //view = "com/zybk/zy_inspection_report/zyInspectionReport-RGB-add";//三级分类为RGB激光
                        } else if (zyIp.getEquipmentSpare ().getType ().getEquipmentType ().getTypeDesc ().equals ( "荧光粉激光" )
                        		 || zyIp.getEquipmentSpare().getType().getEquipmentType().getTypeDesc().equals("X系列")) {
                            reportType = "3";
                            //view = "com/zybk/zy_inspection_report/zyInspectionReport-ygf-add";//三级分类为荧光粉激光
                        } else if (zyIp.getEquipmentSpare ().getType ().getEquipmentType ().getTypeDesc ().equals ( "E系列" )) {
                            reportType = "4";
                            //view = "com/zybk/zy_inspection_report/zyInspectionReport-E-add";//三级分类为E系列
                        } else {
                            reportType = "5";
                            //view = "com/zybk/zy_inspection_report/zyInspectionReport-other-add";//其他机型
                        }
                    } else {
                        reportType = "5";
                        //view = "com/zybk/zy_inspection_report/zyInspectionReport-other-add";//其他机型
                    }
                }
            }
            j.setObj ( reportType );
        }

    }

    @Override
    public void queryDataGridOfSendPlanList(HttpServletRequest request, DataGrid dataGrid) {
        StringBuffer sql = new StringBuffer ();
        sql.append ( " SELECT " );
        sql.append ( " 	ip.id, " );
        sql.append ( " 	ip.plan_id AS planId, " );
        sql.append ( " 	CONCAT( " );
        sql.append ( " 		ptt.territoryname, " );
        sql.append ( " 		',', " );
        sql.append ( " 		tt.territoryname " );
        sql.append ( " 	) AS tsTerritoryVal, " );
        sql.append ( " 	tt.territoryname AS 'equipmentSpare.tsTerritory.territoryName', " );
        sql.append ( " 	es.sn AS 'equipmentSpare.sn', " );
        sql.append ( " 	cm. NAME AS 'equipmentSpare.zyCinema.name', " );
        sql.append ( " 	cm.address AS 'equipmentSpare.zyCinema.address', " );
        sql.append ( " 	ip.company, " );
        sql.append ( " 	es.bp_no AS 'equipmentSpare.bpNo', " );
        sql.append ( " 	ip.plan_quarter AS 'planQuarter', " );
        sql.append ( " 	es.laser_reconstruction AS 'equipmentSpare.laserReconstruction', " );
        sql.append ( " 	eg.`name` AS 'engineer.name', " );
        sql.append ( " 	ip.actual_date AS actualDate, " );
        sql.append ( " 	ct.`name` AS 'contacter.name', " );
        sql.append ( " 	DATE_FORMAT( " );
        sql.append ( " 		es.last_year_inspection_date, " );
        sql.append ( " 		'%Y-%m-%d' " );
        sql.append ( " 	) AS 'equipmentSpare.lastYearInspectionDate', " );
        sql.append ( " 	CONCAT( " );
        sql.append ( " 		DATE_FORMAT( " );
        sql.append ( " 			ip.order_begin_time, " );
        sql.append ( " 			'%Y-%m-%d' " );
        sql.append ( " 		), " );
        sql.append ( " 		'~', " );
        sql.append ( " 		DATE_FORMAT( " );
        sql.append ( " 			ip.order_end_time, " );
        sql.append ( " 			'%Y-%m-%d' " );
        sql.append ( " 		) " );
        sql.append ( " 	) AS orderBeginToEndVal, " );
        sql.append ( " 	ip.engineer_order_time AS engineerOrderTime, " );
        sql.append ( " 	ip.state " );
        sql.append ( " FROM " );
        sql.append ( " 	zy_inspection_plan ip " );
        sql.append ( " LEFT JOIN zy_equipment_spare es ON es.id = ip.equipment_spare_id " );
        sql.append ( " LEFT JOIN t_s_territory tt ON tt.id = es.city_id " );
        sql.append ( " LEFT JOIN t_s_territory ptt ON ptt.id = tt.territoryparentid " );
        sql.append ( " LEFT JOIN zy_cinema cm ON cm.id = es.belong_cinema_id " );
        sql.append ( " LEFT JOIN zy_engineer eg ON eg.id = ip.engineer " );
        sql.append ( " LEFT JOIN zy_contacts ct ON ct.id = ip.charge_person " );
        dataGrid.setResults ( findForJdbc ( sql.toString () ) );
    }

    @Override
    public boolean judgeForAreaEngineerAssignEngineer(String id, AjaxJson j, String userId) {
        ZyInspectionPlanEntity zyIP = systemService.get ( ZyInspectionPlanEntity.class, id );
        String message = "";
        boolean flag = true;
        //区域工程师只能分配 第三方已分配，工程师拒绝 的巡检任务
        if(null!=zyIP&&null!=zyIP.getAreaEngineer ()&&null!=zyIP.getAreaEngineer ().getTsBaseUser ()){
            if (zyIP.getAreaEngineer ().getTsBaseUser ().getId ().equals ( userId )) {
                if (!zyIP.getState ().equals ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED )
                        && !zyIP.getState ().equals ( StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED )) {
                    flag = false;
                    message = "所选任务中包括不能操作的任务，请重新选择";
                }
            } else {
                flag = false;
                message = "当前巡检任务已指派其它区域工程师";
            }
        }else{
            flag = false;
            message = "当前巡检任务没有区域工程师";
        }
        if (null != j) {
            j.setMsg ( message );
            j.setSuccess ( flag );
        }
        return flag;
    }

    @Override
    public boolean judgeForAreaEngineerAssignEngineerPlan(String id, AjaxJson j, String userId) {
        ZyInspectionPlanEntity zyIP = systemService.get ( ZyInspectionPlanEntity.class, id );
        String message = "";
        boolean flag = true;
        //区域工程师只能分配 第三方已分配，工程师拒绝 的巡检任务
        if(null!=zyIP&&null!=zyIP.getAreaEngineer ()&&null!=zyIP.getAreaEngineer ().getTsBaseUser ()){
            if (zyIP.getAreaEngineer ().getTsBaseUser ().getId ().equals ( userId )) {
                if (!zyIP.getState ().equals ( StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED )
                        && !zyIP.getState ().equals ( StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED)
                        && !zyIP.getState ().equals ( StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED )) {
                    flag = false;
                    message = "所选任务中包括不能操作的任务，请重新选择";
                }
            } else {
                flag = false;
                message = "当前巡检任务已指派其它区域工程师";
            }
        }else{
            flag = false;
            message = "当前巡检任务没有区域工程师";
        }
        if (null != j) {
            j.setMsg ( message );
            j.setSuccess ( flag );
        }
        return flag;
    }

    @Override
    public List<String> getPlanIdsByIrExReportConditions(String ipEndTimeYear,
                                                         String ipEndTimeMonth) {
        StringBuffer sql = new StringBuffer ();
        sql.append ( " SELECT " );
        sql.append ( "    ip.id AS planId " );
        sql.append ( " FROM " );
        sql.append ( "    zy_inspection_plan ip " );
        sql.append ( " WHERE " );
        sql.append ( "    YEAR (ip.end_time) = '" ).append ( ipEndTimeYear ).append ( "' " );
        sql.append ( "    AND ip.state = '" ).append ( StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE ).append ( "' " );
        if (StringUtil.isNotEmpty ( ipEndTimeMonth )) {
            sql.append ( " AND MONTH (ip.end_time) = '" ).append ( ipEndTimeMonth ).append ( "' " );
        }
        List<Map<String, Object>> rs = systemService.findForJdbc ( sql.toString () );
        List<String> planIds = new ArrayList<String> ();
        for (Map<String, Object> map : rs) {
            planIds.add ( map.get ( "planId" ).toString () );
        }
        return planIds;
    }


}